Passed
Pull Request — master (#213)
by
unknown
33:41 queued 23:20
created

kitodopublication.js ➔ setAutocomplete   C

Complexity

Conditions 8

Size

Total Lines 67
Code Lines 44

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 44
dl 0
loc 67
rs 6.9573
c 0
b 0
f 0
cc 8

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
/**
2
 * This file is part of the TYPO3 CMS project.
3
 *
4
 * It is free software; you can redistribute it and/or modify it under
5
 * the terms of the GNU General Public License, either version 2
6
 * of the License, or any later version.
7
 *
8
 * For the full copyright and license information, please read the
9
 * LICENSE.txt file that was distributed with this source code.
10
 *
11
 * The TYPO3 project - inspiring people to share!
12
 */
13
14
var userNotifcationSettings = {
15
    init: function() {
16
17
        if (!jQuery("#notifyOnChanges").prop("checked")) {
18
            jQuery(".notifyOnChanges-child").prop("disabled","true");
19
        }
20
21
        jQuery("#notifyOnChanges").on("click", function(){
22
            if (jQuery(this).prop("checked")) {
23
                jQuery(this).parent().find(".notifyOnChanges-child").prop("disabled",false);
24
            } else {
25
                jQuery(this).parent().find(".notifyOnChanges-child").prop("disabled",true);
26
            }
27
        });
28
    }
29
}
30
var documentFormGroupSelector = {
31
    init() {
32
        var form = jQuery(".document-form-main");
33
        if (typeof form !== "undefined" && form.length > 0) {
34
35
            var activeGroup = form.data("activegroup");
36
            var activeGroupIndex = form.data("activegroupindex");
37
38
            var tab = jQuery('fieldset[data-group="' + activeGroup + '"]').parent().attr("id");
39
40
            if (typeof tab !== "undefined" && tab.length > 0) {
41
                jQuery('.nav-link').removeClass("active");
42
                jQuery('.tab-pane').removeClass("active");
43
                jQuery('.nav-link[href="#' + tab + '"]').addClass("active");
44
                jQuery('fieldset[data-group="' + activeGroup + '"]').parent().addClass("active");
45
46
                if (activeGroupIndex >= 0) {
47
                    var group = jQuery('fieldset[data-group="' + activeGroup + '"]:eq(' + activeGroupIndex + ')');
48
                    jQuery('html, body').animate({
49
                        scrollTop: jQuery(group).offset().top - 150
50
                    }, 0);
51
                } else {
52
                    var emptyGroupElement = jQuery('fieldset[data-group="' + activeGroup + '"][data-emptygroup="1"]').first();
53
54
                    if (emptyGroupElement.length > 0) {
55
                        activeGroupIndex = emptyGroupElement.data('groupindex');
56
                    } else {
57
                        activeGroupIndex = jQuery('fieldset[data-group="' + activeGroup + '"]').size();
58
                    }
59
60
                    if (activeGroupIndex > 0) {
61
                        addGroup(jQuery('button.add_group[data-group="' + activeGroup + '"]'));
62
                    }
63
64
                    if (form.data("addcurrentfeuser")) {
65
                        isGroupLoaded(
66
                            'fieldset[data-group="' + activeGroup + '"][data-groupindex="' + activeGroupIndex + '"]',
67
                            function () {
68
                                jQuery('.addMyData').hide();
69
                                var activeGroupElement = jQuery('fieldset[data-group="' + activeGroup + '"][data-groupindex="' + activeGroupIndex + '"]');
70
                                //var context = jQuery('#userSearchModal-'+activeGroupIndex).find('input');
71
                                var context = activeGroupElement.find('.addMyData').first();
72
                                setDataRequest(context.data('ajax'), jQuery('form').data('fispersid'), context);
73
                                jQuery('<div class="alert alert-warning" role="alert"><i class="fas fa-exclamation-triangle pull-right"></i>' + form_info_msg_personid_added + '</div>').insertAfter(activeGroupElement.find('legend').last());
0 ignored issues
show
Bug introduced by
The variable form_info_msg_personid_added seems to be never declared. If this is a global, consider adding a /** global: form_info_msg_personid_added */ comment.

This checks looks for references to variables that have not been declared. This is most likey a typographical error or a variable has been renamed.

To learn more about declaring variables in Javascript, see the MDN.

Loading history...
74
                                jQuery('html, body').animate({
75
                                    scrollTop: jQuery(activeGroupElement).offset().top - 150
76
                                }, 0);
77
                            });
78
                    }
79
                }
80
            }
81
        }
82
    }
83
}
84
85
var isGroupLoaded = function (element, callback, counter = 0) {
86
    if (jQuery(element).length) {
87
        callback(jQuery(element));
88
    } else {
89
        if (counter < 10) {
90
            setTimeout(function () {
91
                isGroupLoaded(element, callback, counter++)
92
            }, 500);
93
        }
94
    }
95
}
96
97
var toggleBulkImportRecord = function() {
98
    jQuery(".bulk-import-checkbox").on("click", function() {
99
        var ajaxURL = jQuery(this).closest("tr").data('ajax');
100
        var params = {};
101
        jQuery.post(ajaxURL, params, function(data) {
0 ignored issues
show
Unused Code introduced by
The parameter data is not used and could be removed.

This check looks for parameters in functions that are not used in the function body and are not followed by other parameters which are used inside the function.

Loading history...
102
        });
103
    });
104
}
105
106
var toggleBulkImportAuthorSearch = function() {
107
    jQuery(".bulkImportAuthorSearch").on("click", function() {
108
        var ajaxURL = jQuery(this).data('ajax');
109
        var params = {};
110
        jQuery.post(ajaxURL, params, function(data) {
0 ignored issues
show
Unused Code introduced by
The parameter data is not used and could be removed.

This check looks for parameters in functions that are not used in the function body and are not followed by other parameters which are used inside the function.

Loading history...
111
        });
112
    });
113
}
114
115
var doctypeChange = {
116
117
    init() {
118
        var _this = this;
0 ignored issues
show
Unused Code introduced by
The variable _this seems to be never used. Consider removing it.
Loading history...
119
120
        jQuery("#confirmDoctypeChange .saveDocumentSummary").on("click", function (e) {
121
122
            var copyText = jQuery("#confirmDoctypeChange .modal-body .details-view").html();
123
124
            copyText = "<!DOCTYPE html>" +
125
                "<html lang=\"de\" dir=\"ltr\" class=\"no-js\">"+
126
                "<head>" +
127
                "<style>" +
128
                    ".details-group-name, .details-field-name {font-weight: bold;} " +
129
                    ".details-group-name {margin: 20px 0 5px 0; font-size: 18px} " +
130
                    ".details-field-name {font-size: 16px;} " +
131
                    ".details-group {list-style: none;}" +
132
                "</style>" +
133
                "</head>" +
134
                "<body>" + copyText + "</body>" +
135
                "</html>";
136
137
            var publication = new Blob([copyText], {type: "text/html;charset=utf-8"});
0 ignored issues
show
Bug introduced by
The variable Blob seems to be never declared. If this is a global, consider adding a /** global: Blob */ comment.

This checks looks for references to variables that have not been declared. This is most likey a typographical error or a variable has been renamed.

To learn more about declaring variables in Javascript, see the MDN.

Loading history...
138
            saveAs(publication, "publication.html");
139
140
            e.preventDefault();
141
        });
142
143
        jQuery("#confirmDoctypeChange .submitChangeDocumentType").on("click", function (e) {
144
            var documentType = jQuery('#changeDocumentTypeForm').find('select').val();
145
            if (documentType <= 0) {
146
                jQuery('#changeDocumentTypeForm').find('select').addClass('mandatory-error');
147
148
                jQuery('.modal-body').animate({
149
                    scrollTop:jQuery(jQuery('#changeDocumentTypeForm').find('select')).offset()
150
                }, 100);
151
152
                e.preventDefault();
153
            }
154
        });
155
156
        jQuery("#changeDocumentTypeForm select").on("change", function (e) {
157
            var documentType = jQuery('#changeDocumentTypeForm').find('select').val();
158
            if (documentType > 0) {
159
                jQuery('#changeDocumentTypeForm').find('select').removeClass('mandatory-error');
160
                e.preventDefault();
161
            }
162
        });
163
164
        jQuery("#confirmDoctypeChange").on("show.bs.modal", function(e) {
165
            jQuery(this).find("#changeDocumentTypeForm").attr("action", jQuery(e.relatedTarget).attr("href"));
166
        });
167
168
        jQuery("#confirmDoctypeChange").on("hidden.bs.modal", function(e) {
0 ignored issues
show
Unused Code introduced by
The parameter e is not used and could be removed.

This check looks for parameters in functions that are not used in the function body and are not followed by other parameters which are used inside the function.

Loading history...
169
            jQuery('#changeDocumentTypeForm').find('select').removeClass('mandatory-error');
170
        });
171
    }
172
}
173
174
var documentFormGroupSelector = {
0 ignored issues
show
Comprehensibility Naming Best Practice introduced by
The variable documentFormGroupSelector already seems to be declared on line 30. Consider using another variable name or omitting the var keyword.

This check looks for variables that are declared in multiple lines. There may be several reasons for this.

In the simplest case the variable name was reused by mistake. This may lead to very hard to locate bugs.

If you want to reuse a variable for another purpose, consider declaring it at or near the top of your function and just assigning to it subsequently so it is always declared.

Loading history...
175
    init() {
176
        var form = jQuery(".document-form-main");
177
        if (typeof form !== "undefined" && form.length > 0) {
178
179
            var activeGroup = form.data("activegroup");
180
            var activeGroupIndex = form.data("activegroupindex");
181
182
            var tab = jQuery('fieldset[data-group="' + activeGroup + '"]').parent().attr("id");
183
184
            if (typeof tab !== "undefined" && tab.length > 0) {
185
                jQuery('.nav-link').removeClass("active");
186
                jQuery('.tab-pane').removeClass("active");
187
                jQuery('.nav-link[href="#' + tab + '"]').addClass("active");
188
                jQuery('fieldset[data-group="' + activeGroup + '"]').parent().addClass("active");
189
190
                if (activeGroupIndex >= 0) {
191
                    group = jQuery('fieldset[data-group="' + activeGroup + '"]:eq(' + activeGroupIndex + ')');
0 ignored issues
show
Bug introduced by
The variable group seems to be never declared. Assigning variables without defining them first makes them global. If this was intended, consider making it explicit like using window.group.
Loading history...
192
                    jQuery('html, body').animate({
193
                        scrollTop: jQuery(group).offset().top - 150
194
                    }, 0);
195
                } else {
196
                    addGroup(jQuery('button.add_group[data-group="' + activeGroup + '"]'));
197
                }
198
            }
199
        }
200
    }
201
}
202
203
var saveExtendedSearch = {
204
205
    init: function () {
206
        this.show();
207
        this.save();
208
209
        jQuery("button").on("click", function () {
210
            jQuery(".alert-save-extended-search-success").hide();
211
        });
212
213
    },
214
215
    show: function() {
216
        jQuery("#save-extended-search").on("click", function (e) {
217
            jQuery('.alert-save-extended-search').hide();
218
            jQuery("#save-extended-search-dialog #extended-search-name").val("");
219
            jQuery("#save-extended-search-dialog").modal('show');
220
            e.preventDefault();
221
        });
222
    },
223
224
    save: function() {
225
        jQuery("#save-extended-search-dialog .modal-submit-button").on("click", function (e) {
0 ignored issues
show
Unused Code introduced by
The parameter e is not used and could be removed.

This check looks for parameters in functions that are not used in the function body and are not followed by other parameters which are used inside the function.

Loading history...
226
            var name = jQuery("#save-extended-search-dialog #extended-search-name").val();
227
            var query = jQuery("#extended-search-query").val();
228
            var ajaxURL = jQuery(this).data('ajax');
229
230
            if (query.length < 1 || name.length < 1) {
231
                jQuery('.alert-save-extended-search').show();
232
                return;
233
            }
234
235
            var res = ajaxURL.match(/(tx\w+?)%/); // get param name
236
            var params = {};
237
            var indexParam = {};
238
            if (res && res[1]) {
239
                indexParam['name'] = name;
240
                indexParam['query'] = query;
241
                params[res[1]] = indexParam;
242
            }
243
244
            jQuery.post(ajaxURL, params, function(data) {
0 ignored issues
show
Unused Code introduced by
The parameter data is not used and could be removed.

This check looks for parameters in functions that are not used in the function body and are not followed by other parameters which are used inside the function.

Loading history...
245
                jQuery("#save-extended-search-dialog").modal('hide');
246
                jQuery(".alert-save-extended-search-success").show();
247
                openExtendedSearch.loadList();
248
            }).fail(function() {
249
250
            })
251
        });
252
    }
253
}
254
255
256
var openExtendedSearch = {
257
258
    init: function () {
259
        this.loadList();
260
    },
261
262
    loadList: function() {
263
        var _this = this;
264
265
        if (jQuery("#load-extended-search").length) {
266
            var ajaxURL = jQuery("#load-extended-search-select").data('ajax');
267
            var params = {};
268
            jQuery.post(ajaxURL, params, function(data) {
269
                jQuery("#load-extended-search-select").length
0 ignored issues
show
introduced by
The result of the property access to jQuery("#load-extended-search-select").length is not used.
Loading history...
270
271
                jQuery("#load-extended-search-select .dropdown-item").remove();
272
273
                data.forEach(function(item){
274
                    if (item.name.length) {
275
                        jQuery(
276
                            '<a class="dropdown-item" ' +
277
                            'data-search-id="' + item.uid + '" ' +
278
                            'href="#">' + item.name + '</a>'
279
                        ).appendTo("#load-extended-search-select");
280
                    }
281
                });
282
283
                if (data.length) {
284
                    jQuery("#load-extended-search").removeAttr("disabled");
285
                } else {
286
                    jQuery("#load-extended-search").attr("disabled","disabled");
287
                }
288
289
                _this.onLoadSearch();
290
291
            }, "json");
292
        }
293
    },
294
295
    onLoadSearch: function() {
296
        jQuery("#load-extended-search-select .dropdown-item").on("click", function (e) {
297
            var ajaxURL = jQuery("#load-extended-search-select").data('ajax-load');
298
            var res = ajaxURL.match(/(tx\w+?)%/);
299
            var params = {};
300
            var indexParam = {};
301
            if (res && res[1]) {
302
                indexParam['id'] = jQuery(this).data("search-id");
303
                params[res[1]] = indexParam;
304
            }
305
306
            jQuery.post(ajaxURL, params, function(data) {
307
                jQuery("#extended-search-query").val(data);
308
            });
309
310
            e.preventDefault();
311
        });
312
    }
313
}
314
315
316
var extendedSearch = {
317
318
    init: function () {
319
        this.showAddFieldDialog();
320
        this.addField();
321
    },
322
323
    showAddFieldDialog: function () {
324
        jQuery("#extended-search-add-field .dropdown-item").on("click", function (e) {
325
            var field = jQuery(this).data("field");
326
            var formGroup = jQuery(this).data("form-group");
327
            var fieldType = jQuery(this).data("type");
328
            var fieldName = jQuery(this).text();
329
330
            jQuery("#add-searchfield-dialog .modal-field-name").text(fieldName);
331
            jQuery("#add-searchfield-dialog .modal-submit-button").data("field", field);
332
            jQuery("#add-searchfield-dialog .modal-submit-button").data("form-group", formGroup);
333
            jQuery("#add-searchfield-dialog .modal-submit-button").data("type", fieldType);
334
335
            jQuery("#add-searchfield-dialog").find(".search-field").addClass("d-none");
336
            jQuery("#add-searchfield-dialog").find(".search-field-" + formGroup).removeClass("d-none");
337
338
            // Reset operators
339
            jQuery("#add-searchfield-dialog #search-field-operator-binary option[value='AND']").prop('selected', true);
340
            jQuery("#add-searchfield-dialog #search-field-operator-unary option[value='']").prop('selected', true);
341
342
            // Reset field values
343
            jQuery("#add-searchfield-dialog .search-field-value").val("");
344
345
            jQuery(".modal-footer").find("[data-target='#FisSearchModal-persons']").hide();
346
            jQuery(".modal-footer").find("[data-target='#FisSearchModal-affiliation']").hide();
347
348
            if (field == 'persons') {
349
                jQuery(".modal-footer").find("[data-target='#FisSearchModal-persons']").show();
350
            }
351
352
            if (field == 'affiliation') {
353
                jQuery(".modal-footer").find("[data-target='#FisSearchModal-affiliation']").show();
354
            }
355
356
            jQuery("#add-searchfield-dialog").modal('show');
357
358
            e.preventDefault();
359
        });
360
    },
361
362
    addField: function () {
363
364
        var _this = this;
365
366
        jQuery("#add-searchfield-dialog .modal-submit-button").on("click", function (e) {
367
            var field = jQuery(this).data("field");
368
            var fieldType = jQuery(this).data("type");
369
            var formGroup = jQuery(this).data("form-group");
370
371
            var operatorBinary = jQuery("#search-field-operator-binary").val();
372
            var operatorUnary = jQuery("#search-field-operator-unary").val();
373
374
            var fieldPart = "";
375
376
            switch(fieldType) {
377
                case "date-range":
378
                    fieldPart = _this.dateRangeField(formGroup, field);
379
                    break;
380
                case "year-range":
381
                    fieldPart = _this.yearRangeField(formGroup, field);
382
                    break;
383
                case "phrase":
384
                    fieldPart = _this.valueField(formGroup, field, true);
385
                    break;
386
                default:
387
                    fieldPart = _this.valueField(formGroup, field);
388
                    break;
389
            }
390
391
            if (fieldPart.length > 0) {
392
393
                var query = jQuery("#extended-search-query").val();
394
395
                if (query.length > 0) {
396
                    query += (operatorBinary) ? " " + operatorBinary + " " : " AND ";
397
                }
398
399
                if (operatorUnary == "NOT") {
400
                    fieldPart = "NOT(" + fieldPart + ")";
401
                }
402
403
                query += fieldPart;
404
405
                jQuery("#extended-search-query").val(query);
406
            }
407
408
            jQuery("#add-searchfield-dialog").modal('hide');
409
            e.preventDefault();
410
        });
411
    },
412
413
    valueField: function(group, field, phrase = false) {
414
415
        var value = jQuery(".search-field-"+group+" .search-field-value").val();
416
417
        if (phrase) {
418
            value = '"'+value+'"';
419
        }
420
421
        var fieldPart = "";
422
423
        if (value.length > 0) {
424
425
            fieldPart += field + ":" + value;
426
        }
427
428
        return fieldPart;
429
    },
430
431
    yearRangeField: function(group, field) {
432
433
        var from = jQuery(".search-field-"+group+" .search-field-from").val();
434
        var to =   jQuery(".search-field-"+group+" .search-field-to").val();
435
436
        var fieldPart = "";
437
438 View Code Duplication
        if (from.length > 0 && to.length > 0) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
439
            fieldPart = field+":["+from+" TO "+to+"]";
440
        } else {
441
            if (from.length == 0 && to.length == 0) {
0 ignored issues
show
Best Practice introduced by
Comparing from.length to 0 using the == operator is not safe. Consider using === instead.
Loading history...
Best Practice introduced by
Comparing to.length to 0 using the == operator is not safe. Consider using === instead.
Loading history...
442
                return "";
443
            }
444
445
            from = (from.length > 0)? from : "*";
446
            to = (to.length > 0)? to : "*";
447
            fieldPart = field+":["+from+" TO "+to+"]";
448
        }
449
450
        return fieldPart;
451
    },
452
453
454
    dateRangeField: function(group, field) {
455
456
        var from = jQuery(".search-field-"+group+" .search-field-from").val();
457
        var to =   jQuery(".search-field-"+group+" .search-field-to").val();
458
459
        var fieldPart = "";
460
461
        var fromDate = moment(from, "DD.MM.YYYY");
462
        if (fromDate.format("DD.MM.YYYY") == from) {
463
            from = fromDate.format("YYYY-MM-DD");
464
        } else {
465
            from = "";
466
        }
467
468
        var toDate = moment(to, "DD.MM.YYYY");
469
        if (toDate.format("DD.MM.YYYY") == to) {
470
            to = toDate.format("YYYY-MM-DD");
471
        } else {
472
            to = "";
473
        }
474
475 View Code Duplication
        if (from.length > 0 && to.length > 0) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
476
            fieldPart = field+":["+from+" TO "+to+"]";
477
        } else {
478
            if (from.length == 0 && to.length == 0) {
0 ignored issues
show
Best Practice introduced by
Comparing to.length to 0 using the == operator is not safe. Consider using === instead.
Loading history...
Best Practice introduced by
Comparing from.length to 0 using the == operator is not safe. Consider using === instead.
Loading history...
479
                return "";
480
            }
481
482
            from = (from.length > 0)? from : "*";
483
            to = (to.length > 0)? to : "*";
484
            fieldPart = field+":["+from+" TO "+to+"]";
485
        }
486
487
        return fieldPart;
488
    }
489
}
490
491
function getWorkspaceListAction() {
492
    return jQuery("#batchForm").attr("data-workspace-list-action");
493
}
494
495
496
var selectFilter = function(selectFilterId, searchInput = false) {
497
    selectFilterId = '#'+selectFilterId;
498
499
    var options = {};
500
    if (!searchInput) {
501
        options['minimumResultsForSearch'] = 'Infinity';
502
    }
503
504
    jQuery(selectFilterId).select2(options);
505
506
    jQuery(selectFilterId).on("select2:select", function(e) {
507
        var data = e.params.data;
508
509
510
        var filterName = jQuery(selectFilterId).attr('name');
511
        var filterValue = [];
512
        if (e.params.data.id) {
513
            filterValue = [e.params.data.id];
514
        }
515
        var ajaxURL = jQuery(selectFilterId).parent().data('ajax');
516
517
        var res = ajaxURL.match(/(tx\w+?)%/); // get param name
518
        var params = {};
519
        var indexParam = {};
520
        if (res && res[1]) {
521
            indexParam['name'] = filterName;
522
            indexParam['values'] = filterValue;
523
            params[res[1]] = indexParam;
524
        }
525
526
        jQuery.post(ajaxURL, params, function(data) {
0 ignored issues
show
Unused Code introduced by
The parameter data is not used and could be removed.

This check looks for parameters in functions that are not used in the function body and are not followed by other parameters which are used inside the function.

Loading history...
527
            window.location.href = getWorkspaceListAction();
528
        });
529
530
    });
531
}
532
533
534
var toggleDiscardedFilter = function() {
535
    jQuery("#hideDiscarded").on("click", function() {
536
        var ajaxURL = jQuery(this).data('ajax');
537
        var params = {};
538
        jQuery.post(ajaxURL, params, function(data) {
0 ignored issues
show
Unused Code introduced by
The parameter data is not used and could be removed.

This check looks for parameters in functions that are not used in the function body and are not followed by other parameters which are used inside the function.

Loading history...
539
            window.location.href = getWorkspaceListAction();
540
        });
541
542
    });
543
}
544
545
var toggleBookmarksOnly = function() {
546
    jQuery("#bookmarksOnly").on("click", function() {
547
        var ajaxURL = jQuery(this).data('ajax');
548
        var params = {};
549
        jQuery.post(ajaxURL, params, function(data) {
0 ignored issues
show
Unused Code introduced by
The parameter data is not used and could be removed.

This check looks for parameters in functions that are not used in the function body and are not followed by other parameters which are used inside the function.

Loading history...
550
            window.location.href = getWorkspaceListAction();
551
        });
552
553
    });
554
}
555
556
557
var selectSort = function() {
558
    jQuery(".sort-button").on("click", function(element){
0 ignored issues
show
Unused Code introduced by
The parameter element is not used and could be removed.

This check looks for parameters in functions that are not used in the function body and are not followed by other parameters which are used inside the function.

Loading history...
559
560
        var field = jQuery(this).attr('data-field');
561
        var order = jQuery(this).attr('data-order');
562
        var ajaxURL = jQuery(this).parent().data('ajax');
563
564
        var res = ajaxURL.match(/(tx\w+?)%/); // get param name
565
        var params = {};
566
        var indexParam = {};
567
        if (res && res[1]) {
568
            indexParam['field'] = field;
569
            indexParam['order'] = order;
570
            params[res[1]] = indexParam;
571
        }
572
573
        jQuery.post(ajaxURL, params, function(data) {
0 ignored issues
show
Unused Code introduced by
The parameter data is not used and could be removed.

This check looks for parameters in functions that are not used in the function body and are not followed by other parameters which are used inside the function.

Loading history...
574
            window.location.href = getWorkspaceListAction();
575
        });
576
    })
577
}
578
579
580
var batchConfirmDialog = function(actionName) {
581
582
    jQuery("#batchButton"+actionName).on("click", function(e) {
583
        jQuery("#batchAction"+actionName).removeAttr("disabled")
584
        jQuery("#confirmWorkspace"+actionName).modal('show');
585
        e.preventDefault();
586
    });
587
588
    jQuery("#confirmWorkspace"+actionName).on('hidden.bs.modal', function(){
589
        jQuery(".batchAction").attr("disabled","disabled")
590
    });
591
}
592
593
var addBookmarkHandler = {
594
    init() {
595
        jQuery(".add-bookmark").on("click", function(e) {
596
            var button = jQuery(this);
597
            var ajaxURL = jQuery(this).data('ajax');
598
            var identifier = jQuery(this).data('id');
599
600
            var res = ajaxURL.match(/(tx\w+?)%/); // get param name
601
            var params = {};
602
            var indexParam = {};
603
            if (res && res[1]) {
604
                indexParam['identifier'] = identifier;
605
                params[res[1]] = indexParam;
606
            }
607
608
            jQuery.post(ajaxURL, params, function(data) {
0 ignored issues
show
Unused Code introduced by
The parameter data is not used and could be removed.

This check looks for parameters in functions that are not used in the function body and are not followed by other parameters which are used inside the function.

Loading history...
609
                button.find("span").removeClass("d-none");
610
            }).done(function() {
611
                setTimeout(function() {
612
                    button.find("span").addClass("d-none");
613
                    button.addClass("disabled");
614
                }, 500);
615
            }).fail(function() {
616
            }).always(function() {
617
            });
618
619
            e.preventDefault();
620
        });
621
622
    }
623
}
624
625
var removeBookmarkHandler = {
626
    init() {
627
        jQuery(".remove-bookmark").on("click", function(e) {
628
629
            var identifier = jQuery(this).attr("data-id");
630
631
            jQuery("#confirmWorkspaceRemoveBookmark .documentIdentifier").val(identifier);
632
            jQuery("tr[data-id='"+identifier+"']").addClass("table-danger");
633
            jQuery("#confirmWorkspaceRemoveBookmark").modal('show');
634
635
            jQuery("#confirmWorkspaceRemoveBookmark").on('hidden.bs.modal', function(){
636
                jQuery("tr[data-id='"+identifier+"']").removeClass("table-danger");
637
            });
638
639
            e.preventDefault();
640
        });
641
    }
642
}
643
644
var batchSelectHandler = {
645
646
    init() {
647
        var _this = this;
648
649
        this.refreshToggleButtons();
650
651
        jQuery(".workspace-select-toggle").removeClass("d-none");
652
653
        jQuery(".workspace-select-toggle").on("click", function(e){
654
655
            if (jQuery(".batch-checkbox:checked").length) {
656
                jQuery(".batch-checkbox").each(function() {
657
                    jQuery(this).prop("checked", false);
658
                });
659
            } else {
660
                jQuery(".batch-checkbox").each(function() {
661
                    jQuery(this).prop("checked", true);
662
                });
663
            }
664
665
            _this.refreshToggleButtons();
666
667
            e.preventDefault();
668
        });
669
670
        jQuery(".batch-checkbox").on("click", function() {
671
            _this.refreshToggleButtons();
672
        });
673
    },
674
    refreshToggleButtons() {
675
        this.toggleSelectButton();
676
        this.toggleRegisterButton();
677
        this.toggleSetInProgressButton();
678
        this.toggleBatchRemoveButton();
679
        this.toggleBatchReleaseButton();
680
        this.toggleBatchBookmarkButton();
681
    },
682
    toggleSelectButton() {
683
        if (jQuery(".batch-checkbox:checked").length > 0) {
684
            jQuery(".workspace-select-all").show();
685
            jQuery(".workspace-unselect-all").hide();
686
        } else {
687
            jQuery(".workspace-select-all").hide();
688
            jQuery(".workspace-unselect-all").show();
689
        }
690
    },
691
    toggleRegisterButton() {
692
        if (jQuery('#workspace-list [data-alias-state="new"] .batch-checkbox:checked').length > 0) {
693
            jQuery("#batchButtonBatchRegister").removeClass("disabled");
694
        } else {
695
            jQuery("#batchButtonBatchRegister").addClass("disabled");
696
        }
697
    },
698
    toggleSetInProgressButton() {
699
        var numNew = jQuery('#workspace-list tbody tr td[data-alias-state="new"]:first-child .batch-checkbox:checked').length;
700
        var numInProgress = jQuery('#workspace-list tbody tr td[data-alias-state="in_progress"]:first-child .batch-checkbox:checked').length;
701
        var numChecked = jQuery(".batch-checkbox:checked").length;
702
703
        if (numNew + numInProgress < numChecked) {
704
            jQuery("#batchButtonBatchSetInProgress").removeClass("disabled");
705
        } else {
706
            jQuery("#batchButtonBatchSetInProgress").addClass("disabled");
707
        }
708
    },
709
    toggleBatchRemoveButton() {
710
        if (jQuery('#workspace-list [data-bookmark="1"] .batch-checkbox:checked').length > 0) {
711
            jQuery("#batchButtonBatchRemove").removeClass("disabled");
712
        } else {
713
            jQuery("#batchButtonBatchRemove").addClass("disabled");
714
        }
715
    },
716
    toggleBatchBookmarkButton: function() {
717
718
        if (jQuery('#workspace-list .batch-checkbox:checked').length < 1) {
719
            jQuery("#batchButtonBatchBookmark").addClass("disabled");
720
        }
721
722
        jQuery('#workspace-list .batch-checkbox:checked').each(function(){
723
            if (jQuery(this).parent().data("alias-state") != "new") {
724
                jQuery("#batchButtonBatchBookmark").removeClass("disabled");
725
            }
726
        });
727
    },
728
    toggleBatchReleaseButton() {
729
        var countChecked = jQuery('#workspace-list .batch-checkbox:checked').length;
730
        var countCheckedNew = jQuery('#workspace-list [data-alias-state="new"] .batch-checkbox:checked').length;
731
        var countCheckedReleased = jQuery('#workspace-list [data-alias-state="released"] .batch-checkbox:checked').length;
732
733
        if (countChecked - (countCheckedNew + countCheckedReleased) > 0) {
734
            jQuery("#batchButtonBatchReleaseUnvalidated").removeClass("disabled");
735
            jQuery("#batchButtonBatchReleaseValidated").removeClass("disabled");
736
        } else {
737
            jQuery("#batchButtonBatchReleaseUnvalidated").addClass("disabled");
738
            jQuery("#batchButtonBatchReleaseValidated").addClass("disabled");
739
        }
740
    }
741
}
742
743
var itemsPerPageHandler = {
744
    init() {
745
746
        jQuery("#items-up").on("click", function(e) {
0 ignored issues
show
Unused Code introduced by
The parameter e is not used and could be removed.

This check looks for parameters in functions that are not used in the function body and are not followed by other parameters which are used inside the function.

Loading history...
747
            var itemsPerPage = jQuery("#items-per-page").val();
748
            var items = parseInt(itemsPerPage, 10);
749
750
            if (itemsPerPage == items) {
751
                items += 10;
752
            } else {
753
                items = 10;
754
            }
755
            jQuery("#items-per-page").val(items);
756
        });
757
758
        jQuery("#items-down").on("click", function(e) {
0 ignored issues
show
Unused Code introduced by
The parameter e is not used and could be removed.

This check looks for parameters in functions that are not used in the function body and are not followed by other parameters which are used inside the function.

Loading history...
759
            var itemsPerPage = jQuery("#items-per-page").val();
760
            var items = parseInt(itemsPerPage, 10);
761
762
            if (itemsPerPage === items.toString()) {
763
                items = (items <= 10)? items : items-10;
764
            } else {
765
                items = 10;
766
            }
767
            jQuery("#items-per-page").val(items);
768
        });
769
770
        jQuery("#items-per-page-save").on("click", function(e) {
0 ignored issues
show
Unused Code introduced by
The parameter e is not used and could be removed.

This check looks for parameters in functions that are not used in the function body and are not followed by other parameters which are used inside the function.

Loading history...
771
            var button = jQuery(this);
0 ignored issues
show
Unused Code introduced by
The variable button seems to be never used. Consider removing it.
Loading history...
772
            var ajaxURL = jQuery(this).data('ajax');
773
            var itemsPerPage = jQuery("#items-per-page").val();
774
775
            var items = parseInt(itemsPerPage, 10);
776
777
            if (itemsPerPage !== items.toString() || items < 1) {
778
                items = 10;
779
            }
780
781
            var res = ajaxURL.match(/(tx\w+?)%/); // get param name
782
            var params = {};
783
            var indexParam = {};
784
            if (res && res[1]) {
785
                indexParam['itemsPerPage'] = items;
786
                params[res[1]] = indexParam;
787
            }
788
789
            jQuery.post(ajaxURL, params, function(data) {
0 ignored issues
show
Unused Code introduced by
The parameter data is not used and could be removed.

This check looks for parameters in functions that are not used in the function body and are not followed by other parameters which are used inside the function.

Loading history...
790
                window.location.href = getWorkspaceListAction();
791
            });
792
793
        });
794
795
    }
796
}
797
798
var validateFormAndSave = function() {
799
    jQuery("#validDocument").val("0");
800
    if (validateForm()) {
801
        jQuery("#validDocument").val("1");
802
803
        jQuery("#new-document-form #save").prop("disabled", true);
804
805
        jQuery("#new-document-form").submit();
806
807
        return true;
808
    }
809
    return false;
810
}
811
var validateFormOnly = function() {
812
    if (validateForm()) {
813
        showFormSuccess();
814
    }
815
    return false;
816
}
817
818
var changeMandatory = function (selector, newValue, oldValue) {
819
    var groupSelector = 'fieldset:not([data-' + selector + '=""])';
820
821
    $(groupSelector).each(function () {
822
        var currentFieldset = $(this);
823
        var value = '';
824
        if (checkFilledInputs(currentFieldset)) {
825
            value = newValue;
826
        } else {
827
            value = oldValue;
828
        }
829
        var groupIds = String(currentFieldset.data(selector)).split(',');
830
        groupIds.forEach(function (entry) {
831
            $('fieldset[data-group="' + entry + '"]').attr('data-mandatory', value);
832
        });
833
    });
834
}
835
836
var validateForm = function() {
837
    var error = false;
838
    jQuery("span.mandatory-error").remove();
839
    jQuery("div.alert").remove();
840
    jQuery(".tx-dpf-tabs li a").each(function() {
841
        jQuery(this).removeClass("mandatory-error");
842
    });
843
    jQuery(".input-field[data-mandatory]").each(function() {
844
        jQuery(this).removeClass("mandatory-error");
845
    });
846
847
    // change mandatory if configuration is set
848
    changeMandatory('optionalgroups', 1, 0);
849
    changeMandatory('requiredgroups', 0, 1);
850
851
    // check mandatory groups
852
    var search = 'fieldset[data-mandatory="'+constants['mandatory']+'"]';
0 ignored issues
show
Bug introduced by
The variable constants seems to be never declared. If this is a global, consider adding a /** global: constants */ comment.

This checks looks for references to variables that have not been declared. This is most likey a typographical error or a variable has been renamed.

To learn more about declaring variables in Javascript, see the MDN.

Loading history...
853
    if (hasFiles()) {
854
        search = search + ',fieldset[data-mandatory="'+constants['mandatory_file_only']+'"]';
855
    }
856
    jQuery(search).each(function() {
857
        var fieldset = jQuery(this);
858
        if (hasMandatoryInputs(fieldset)) {
859
            if (checkMandatoryInputs(fieldset)) {
860
                jQuery('<div class="alert alert-warning" role="alert"><i class="fas fa-exclamation-triangle pull-right"></i>' + form_error_msg_group_mandatory + '</div>').insertAfter(fieldset.find("legend").last());
0 ignored issues
show
Bug introduced by
The variable form_error_msg_group_mandatory seems to be never declared. If this is a global, consider adding a /** global: form_error_msg_group_mandatory */ comment.

This checks looks for references to variables that have not been declared. This is most likey a typographical error or a variable has been renamed.

To learn more about declaring variables in Javascript, see the MDN.

Loading history...
861
                showFormError();
862
                error = true;
863
                markPage(fieldset, true);
864
            }
865
        } else {
866
            if (checkFilledInputs(fieldset)) {
867
                jQuery('<div class="alert alert-warning" role="alert"><i class="fas fa-exclamation-triangle pull-right"></i>' + form_error_msg_group_one_required + '</div>').insertAfter(fieldset.find("legend").last());
0 ignored issues
show
Bug introduced by
The variable form_error_msg_group_one_required seems to be never declared. If this is a global, consider adding a /** global: form_error_msg_group_one_required */ comment.

This checks looks for references to variables that have not been declared. This is most likey a typographical error or a variable has been renamed.

To learn more about declaring variables in Javascript, see the MDN.

Loading history...
868
                showFormError();
869
                error = true;
870
                markPage(fieldset, true);
871
                error = true;
872
            }
873
        }
874
    });
875
    jQuery("fieldset[id=primary_file]").each(function() {
876
        var fieldset = jQuery(this);
877
        if (checkPrimaryFile(fieldset)) {
878
            jQuery('<div class="alert alert-warning" role="alert"><i class="fas fa-exclamation-triangle pull-right"></i>' + form_error_msg_group_mandatory + '</div>').insertBefore(fieldset.find("legend").last());
0 ignored issues
show
Bug introduced by
The variable form_error_msg_group_mandatory seems to be never declared. If this is a global, consider adding a /** global: form_error_msg_group_mandatory */ comment.

This checks looks for references to variables that have not been declared. This is most likey a typographical error or a variable has been renamed.

To learn more about declaring variables in Javascript, see the MDN.

Loading history...
879
            showFormError();
880
            error = true;
881
            markPage(fieldset, true);
882
        }
883
    });
884
    // check non mandatory groups
885
    jQuery('fieldset[data-mandatory=""],fieldset[data-mandatory="0"]').each(function() {
886
        var fieldset = jQuery(this);
887
        var filledInputs = 0;
888
        jQuery(this).find(".input-field").each(function() {
889
            var id = jQuery(this).attr("id");
890
            if (
891
                ((jQuery(this).attr("type") != "checkbox" && jQuery(this).val()) || (jQuery(this).attr("type") == "checkbox" && (jQuery("#" + id + ":checked").length > 0))) &&
892
                jQuery(this).attr("data-default") != "1"
893
            ) {
894
                filledInputs++;
895
            }
896
            //if (jQuery(this).val() && jQuery(this).attr("data-default") != "1") {
897
            //    filledInputs++;
898
            //}
899
            jQuery(this).removeClass("mandatory-error");
900
        });
901
        // if there are fields with a value then mandatory fields
902
        // are relevant.
903
        if (filledInputs) {
904
            if (checkMandatoryInputs(fieldset)) {
905
                jQuery('<div class="alert alert-warning" role="alert"><i class="fas fa-exclamation-triangle pull-right"></i>' + form_error_msg_group_mandatory + '</div>').insertAfter(fieldset.find("legend").last());
0 ignored issues
show
Bug introduced by
The variable form_error_msg_group_mandatory seems to be never declared. If this is a global, consider adding a /** global: form_error_msg_group_mandatory */ comment.

This checks looks for references to variables that have not been declared. This is most likey a typographical error or a variable has been renamed.

To learn more about declaring variables in Javascript, see the MDN.

Loading history...
906
                showFormError();
907
                markPage(fieldset, true);
908
                error = true;
909
            }
910
        }
911
    });
912
    jQuery("fieldset").each(function() {
913
        var fieldset = jQuery(this);
914
        fieldset.find(".input-field").each(function() {
915
            jQuery(this).removeClass("invalid-error");
916
            var validation = jQuery(this).attr("data-regexp");
917
            if (jQuery(this).val() && jQuery(this).val().length > 0 && validation && validation.length > 0) {
918
                try {
919
                    var regexp = new RegExp(validation);
920
                    var res = jQuery(this).val().match(regexp);
921
                    if (!(res && res.length == 1 && res[0] == jQuery(this).val())) {
0 ignored issues
show
Best Practice introduced by
Comparing res.length to 1 using the == operator is not safe. Consider using === instead.
Loading history...
922
                        jQuery('<div class="alert alert-warning" role="alert"><i class="fas fa-exclamation-triangle pull-right"></i>' + form_error_msg_field_invalid + ': ' + jQuery(this).attr("data-label") + '</div>').insertAfter(fieldset.find("legend").last());
0 ignored issues
show
Bug introduced by
The variable form_error_msg_field_invalid seems to be never declared. If this is a global, consider adding a /** global: form_error_msg_field_invalid */ comment.

This checks looks for references to variables that have not been declared. This is most likey a typographical error or a variable has been renamed.

To learn more about declaring variables in Javascript, see the MDN.

Loading history...
923
                        jQuery(this).addClass("invalid-error");
924
                        showFormError();
925
                        markPage(fieldset, true);
926
                        error = true;
927
                    }
928
                } catch (err) {
929
                    jQuery('<div class="alert alert-warning" role="alert"><i class="fas fa-exclamation-triangle pull-right"></i>' + form_error_msg_field_invalid + ': ' + jQuery(this).attr("data-label") + '</div>').insertAfter(fieldset.find("legend").last());
930
                    jQuery(this).addClass("invalid-error");
931
                    showFormError();
932
                    markPage(fieldset, true);
933
                    error = true;
934
                }
935
            } else {
936
                var validateDate = jQuery(this).attr("data-datatype") == 'DATE';
937
                if (jQuery(this).val() && jQuery(this).val().length > 0 && validateDate && !isDate(jQuery(this).val())) {
938
                    jQuery('<div class="alert alert-warning" role="alert"><i class="fas fa-exclamation-triangle pull-right"></i>' + form_error_msg_field_invalid + ': ' + jQuery(this).attr("data-label") + '</div>').insertAfter(fieldset.find("legend").last());
939
                    jQuery(this).addClass("invalid-error");
940
                    showFormError();
941
                    markPage(fieldset, true);
942
                    error = true;
943
                }
944
            }
945
946
            var maxLength = jQuery(this).attr("data-maxlength");
947
            if (maxLength && maxLength > 0) {
948
                if (jQuery(this).val().length > maxLength) {
949
                    var max_lengrth_msg = form_error_msg_field_max_length.replace(/%s/gi, maxLength);
0 ignored issues
show
Bug introduced by
The variable form_error_msg_field_max_length seems to be never declared. If this is a global, consider adding a /** global: form_error_msg_field_max_length */ comment.

This checks looks for references to variables that have not been declared. This is most likey a typographical error or a variable has been renamed.

To learn more about declaring variables in Javascript, see the MDN.

Loading history...
950
                    jQuery('<div class="alert alert-warning" role="alert"><i class="fas fa-exclamation-triangle pull-right"></i>' + max_lengrth_msg + jQuery(this).attr("data-label") + '</div>').insertAfter(fieldset.find("legend").last());
951
                    jQuery(this).addClass("invalid-error");
952
                    showFormError();
953
                    markPage(fieldset, true);
954
                    error = true;
955
                }
956
            }
957
        });
958
    });
959
960
    return !error;
961
}
962
var showFormError = function() {
963
    jQuery(".tx-dpf div.alert-danger").remove();
964
    jQuery('<div class="alert alert-danger" role="alert"><i class="fab fa-gripfire pull-right"></i>' + form_error_msg + '</div>').insertBefore(jQuery(".tx-dpf form.document-form-main").first());
0 ignored issues
show
Bug introduced by
The variable form_error_msg seems to be never declared. If this is a global, consider adding a /** global: form_error_msg */ comment.

This checks looks for references to variables that have not been declared. This is most likey a typographical error or a variable has been renamed.

To learn more about declaring variables in Javascript, see the MDN.

Loading history...
965
    jQuery("html, body").animate({
966
        scrollTop: 0
967
    }, 200);
968
}
969
var showFormSuccess = function() {
970
    jQuery(".tx-dpf div.alert-danger").remove();
971
    jQuery('<div class="alert alert-success" role="alert"><i class="fab fa-gripfire pull-right"></i>' + form_success_msg + '</div>').insertBefore(jQuery(".tx-dpf form.document-form-main").first());
0 ignored issues
show
Bug introduced by
The variable form_success_msg seems to be never declared. If this is a global, consider adding a /** global: form_success_msg */ comment.

This checks looks for references to variables that have not been declared. This is most likey a typographical error or a variable has been renamed.

To learn more about declaring variables in Javascript, see the MDN.

Loading history...
972
    jQuery("html, body").animate({
973
        scrollTop: 0
974
    }, 200);
975
}
976
977
978
var hasFiles = function() {
979
    var $hasFiles = 0;
980
    jQuery(".input_file_upload").each(function() {
981
        if (jQuery(this).val()) {
982
            $hasFiles++;
983
        }
984
    });
985
    jQuery(".fs_file_group .file_link").each(function() {
986
        if (jQuery(this).attr("href")) {
987
            $hasFiles++;
988
        }
989
    });
990
991
    return $hasFiles > 0;
992
}
993
994
var hasMandatoryInputs = function(fieldset) {
995
    var search = '.input-field[data-mandatory="'+constants['mandatory']+'"]';
0 ignored issues
show
Bug introduced by
The variable constants seems to be never declared. If this is a global, consider adding a /** global: constants */ comment.

This checks looks for references to variables that have not been declared. This is most likey a typographical error or a variable has been renamed.

To learn more about declaring variables in Javascript, see the MDN.

Loading history...
996
    if (hasFiles()) {
997
        search = search + ',.input-field[data-mandatory="'+constants['mandatory_file_only']+'"]';
998
    }
999
    var inputs = fieldset.find(search);
1000
    return inputs.length > 0
1001
}
1002
var markPage = function(fieldset, error) {
1003
    var pageId = fieldset.parent().attr("id");
1004
    var page = jQuery('.tx-dpf-tabs li a[href="#' + pageId + '"]');
1005
    if (error) {
1006
        page.addClass("mandatory-error");
1007
    } else {
1008
        page.removeClass("mandatory-error");
1009
    }
1010
}
1011
var checkMandatoryInputs = function(fieldset) {
1012
    var mandatoryError = false;
1013
    var search = '.input-field[data-mandatory="'+constants['mandatory']+'"]';
0 ignored issues
show
Bug introduced by
The variable constants seems to be never declared. If this is a global, consider adding a /** global: constants */ comment.

This checks looks for references to variables that have not been declared. This is most likey a typographical error or a variable has been renamed.

To learn more about declaring variables in Javascript, see the MDN.

Loading history...
1014
    if (hasFiles()) {
1015
        search = search + ',.input-field[data-mandatory="'+constants['mandatory_file_only']+'"]';
1016
    }
1017
    fieldset.find(search).each(function() {
1018
        var id = jQuery(this).attr("id");
1019
        if ((jQuery(this).attr("type") != "checkbox" && !jQuery(this).val()) || (jQuery(this).attr("type") == "checkbox" && (jQuery("#" + id + ":checked").length != 1 || !jQuery("#" + id + ":checked")))) {
0 ignored issues
show
Best Practice introduced by
Comparing jQuery("#" + id + ":checked").length to 1 using the != operator is not safe. Consider using !== instead.
Loading history...
1020
            mandatoryError = mandatoryError || true;
1021
            jQuery(this).addClass("mandatory-error");
1022
        } else {
1023
            jQuery(this).removeClass("mandatory-error");
1024
        }
1025
    });
1026
    return mandatoryError;
1027
}
1028
var checkPrimaryFile = function(fieldset) {
1029
    var mandatoryError = false;
1030
    fieldset.find("input#inp_primaryFile[data-primaryfilemandatory=1]").each(function() {
1031
        if (!jQuery(this).val()) {
1032
            mandatoryError = mandatoryError || true;
1033
            jQuery(this).addClass("mandatory-error");
1034
        } else {
1035
            jQuery(this).removeClass("mandatory-error");
1036
        }
1037
    });
1038
    return mandatoryError;
1039
}
1040
var checkFilledInputs = function(fieldset) {
1041
    var filledInputs = 0;
1042
    fieldset.find(".input-field").each(function() {
1043
        var id = jQuery(this).attr("id");
1044
        if (
1045
            ((jQuery(this).attr("type") != "checkbox" && jQuery(this).val()) || (jQuery(this).attr("type") == "checkbox" && (jQuery("#" + id + ":checked").length > 0))) &&
1046
            jQuery(this).attr("data-default") != "1"
1047
        ) {
1048
            filledInputs++;
1049
        }
1050
        //if (jQuery(this).val()) {
1051
        //    filledInputs++;
1052
        //}
1053
        jQuery(this).removeClass("mandatory-error");
1054
    });
1055
    return filledInputs < 1;
1056
}
1057
var addGroup = function(target, fileGroup = false) {
1058
1059
    var element = jQuery(target);
0 ignored issues
show
Unused Code introduced by
The variable element seems to be never used. Consider removing it.
Loading history...
1060
1061
    var dataGroup = jQuery(target).attr("data-group");
1062
1063
    // Number of the next group item
1064
    var groupIndex = parseInt(jQuery(target).attr("data-groupIndex")) + 1;
1065
1066
    jQuery(target).attr("data-groupIndex", groupIndex);
1067
    var ajaxURL = jQuery(target).attr("data-ajax");
1068
    var params = buildAjaxParams(ajaxURL, "groupIndex", groupIndex);
1069
1070
    //do the ajax-call
1071
    jQuery.post(ajaxURL, params, function(group) {
1072
        var group = jQuery(group).find("fieldset");
1073
        // add the new group
1074
        jQuery(group).css({
1075
            'display': 'none'
1076
        }).insertAfter(jQuery('fieldset[data-group="' + dataGroup + '"]').last());
1077
        var height = jQuery('fieldset[data-group="' + dataGroup + '"]').last().outerHeight(true);
0 ignored issues
show
Unused Code introduced by
The variable height seems to be never used. Consider removing it.
Loading history...
1078
1079
        jQuery(group).fadeIn();
1080
1081
        jQuery("html, body").animate({
1082
            scrollTop: jQuery(group).offset().top - 150
1083
        }, 100);
1084
1085
        buttonFillOutServiceUrn();
1086
        datepicker();
1087
        addRemoveFileButton();
1088
        userSearch(group);
1089
        userSearchModalFillout();
1090
        addMyUserData();
1091
1092
        // gnd autocomplete for new groups
1093
        var gndField = jQuery(group).find(".gnd");
1094
        if (gndField.length != 0) {
0 ignored issues
show
Best Practice introduced by
Comparing gndField.length to 0 using the != operator is not safe. Consider using !== instead.
Loading history...
1095
            setGndAutocomplete(gndField.data("field"),gndField.data("groupindex"));
1096
        }
1097
        loadMdEditor();
1098
1099
        if (fileGroup) {
1100
          jQuery(target).remove();
1101
          //jQuery(".tx-dpf").on("click", ".rem_file_group", deleteFile);
1102
        }
1103
    });
1104
    return false;
1105
}
1106
var addField = function() {
1107
    var addButton = jQuery(this);
1108
    // Get the field uid
1109
    var dataField = jQuery(this).attr("data-field");
0 ignored issues
show
Unused Code introduced by
The variable dataField seems to be never used. Consider removing it.
Loading history...
1110
    // Number of the next field item
1111
    var fieldIndex = parseInt(jQuery(this).attr("data-index")) + 1;
1112
    jQuery(this).attr("data-index", fieldIndex);
1113
    var ajaxURL = jQuery(this).attr("data-ajax");
1114
    var params = buildAjaxParams(ajaxURL, "fieldIndex", fieldIndex);
1115
1116
    //do the ajax-call
1117
    jQuery.post(ajaxURL, params, function(element) {
1118
        var field = jQuery(element).find("#new-element").children();
1119
        jQuery(field).css({
1120
            "display": "none"
1121
        }).insertBefore(addButton).fadeIn();
1122
        buttonFillOutServiceUrn();
1123
        datepicker();
1124
1125
        // gnd autocomplete for new fields
1126
        var gndField = jQuery(element).find(".gnd");
1127
        if (gndField.length != 0) {
0 ignored issues
show
Best Practice introduced by
Comparing gndField.length to 0 using the != operator is not safe. Consider using !== instead.
Loading history...
1128
            setGndAutocomplete(gndField.data("field"),gndField.data("groupindex"));
1129
        }
1130
        loadMdEditor();
1131
    });
1132
    return false;
1133
}
1134
1135
var deleteFile = function() {
1136
    var fileGroup = jQuery(this).parents(".fs_file_group");
1137
1138
    var dataGroup = fileGroup.attr("data-group");
1139
    var dataPage = fileGroup.parent().attr("data-page");
0 ignored issues
show
Unused Code introduced by
The variable dataPage seems to be never used. Consider removing it.
Loading history...
1140
1141
    var numFileGroups = fileGroup.parent().children('.fs_file_group[data-group=' + dataGroup + ']').length;
1142
1143
    var groupIndex = fileGroup.attr("data-groupIndex");
0 ignored issues
show
Unused Code introduced by
The variable groupIndex seems to be never used. Consider removing it.
Loading history...
1144
1145
    if (numFileGroups == 1) {
0 ignored issues
show
Best Practice introduced by
Comparing numFileGroups to 1 using the == operator is not safe. Consider using === instead.
Loading history...
1146
      addGroup(fileGroup, true);
1147
    } else {
1148
      fileGroup.fadeOut(300, function () {
1149
        jQuery(this).remove();
1150
      });
1151
    }
1152
1153
    //var dataIndex = jQuery(this).data("index");
1154
    return false;
1155
}
1156
1157
/*
1158
var deleteFile = function() {
1159
1160
    var fileGroup = jQuery(this).parent().parent();
1161
    var ajaxURL = jQuery(this).attr("data-ajax");
1162
    var params = {}
1163
    //do the ajax-call
1164
    jQuery.post(ajaxURL, params, function(element) {
1165
        var field = jQuery(element).find("#new-element").children();
1166
        jQuery(fileGroup).replaceWith(field);
1167
    });
1168
    return false;
1169
}
1170
1171
*/
1172
function buildAjaxParams(ajaxURL, indexName, index) {
1173
    var res = ajaxURL.match(/(tx\w+?)%/); // get param name
1174
    var params = {};
1175
    var indexParam = {};
1176
    if (res && res[1]) {
1177
        indexParam[indexName] = index;
1178
        params[res[1]] = indexParam;
1179
    }
1180
    return params;
1181
}
1182
1183
var fillOutServiceUrn = function() {
1184
    // Get the field uid
1185
    var fieldUid = jQuery(this).attr("data-field");
1186
    var fieldIndex = jQuery(this).attr("data-index");
1187
    var groupUid = jQuery(this).attr("data-group");
1188
    var groupIndex = jQuery(this).attr("data-groupindex");
1189
    var ajaxURL = jQuery(this).attr("data-ajax");
1190
    var fedoraPid = jQuery("#fedorapid").val();
1191
    var params = {};
0 ignored issues
show
Unused Code introduced by
The assignment to variable params seems to be never used. Consider removing it.
Loading history...
1192
    if (fedoraPid) {
1193
        params = buildAjaxParams(ajaxURL, "fedoraPid", fedoraPid);
1194
    } else {
1195
        params = buildAjaxParams(ajaxURL, "fedoraPid", "");
1196
    }
1197
1198
    var group = $(this).closest(".fs_group");
1199
1200
    //do the ajax-call
1201
    jQuery.post(ajaxURL, params, function(element) {
1202
1203
        group.find(".alert-filloutservice-urn").remove();
1204
1205
        if (element.error) {
1206
            var errorMsg = $('<div class="alert alert-danger alert-filloutservice-urn" role="alert"><i class="fab fa-gripfire pull-right"></i>' + form_error_msg_filloutservice + '</div>');
0 ignored issues
show
Bug introduced by
The variable form_error_msg_filloutservice seems to be never declared. If this is a global, consider adding a /** global: form_error_msg_filloutservice */ comment.

This checks looks for references to variables that have not been declared. This is most likey a typographical error or a variable has been renamed.

To learn more about declaring variables in Javascript, see the MDN.

Loading history...
1207
            errorMsg.insertAfter(group.find("legend"));
1208
            $("html, body").animate({scrollTop: group.offset().top}, 200);
1209
        } else {
1210
            jQuery("#fedorapid").val(element.fedoraPid);
1211
            jQuery("#primaryUrn").val(element.value);
1212
            var inputField = jQuery('.input-field[data-field="' + fieldUid + '"][data-index="' + fieldIndex + '"][data-group="' + groupUid + '"][data-groupindex="' + groupIndex + '"]');
1213
            inputField.val(element.value);
1214
            buttonFillOutServiceUrn();
1215
        }
1216
    }, "json");
1217
1218
    return false;
1219
}
1220
var buttonFillOutServiceUrn = function() {
1221
    jQuery("input.urn").each(function() {
1222
        var fieldUid = jQuery(this).attr("data-field");
1223
        var fieldIndex = jQuery(this).attr("data-index");
1224
        var groupUid = jQuery(this).attr("data-group");
0 ignored issues
show
Unused Code introduced by
The variable groupUid seems to be never used. Consider removing it.
Loading history...
1225
        var groupIndex = jQuery(this).attr("data-groupindex");
0 ignored issues
show
Unused Code introduced by
The variable groupIndex seems to be never used. Consider removing it.
Loading history...
1226
        var fillOutButton = jQuery('.fill_out_service_urn[data-field="' + fieldUid + '"][data-index="' + fieldIndex + '"]');
1227
        if ((jQuery(this).val() && jQuery(this).val().length > 0) || hasPrimaryUrn()) {
1228
            fillOutButton.hide();
1229
        } else {
1230
            fillOutButton.show();
1231
        }
1232
    });
1233
    return false;
1234
}
1235
var hasPrimaryUrn = function() {
1236
    var result = false;
1237
    var primaryUrn = jQuery("#primaryUrn").val();
1238
    jQuery("input.urn").each(function() {
1239
        var currentUrn = jQuery(this).val();
1240
        if (currentUrn && primaryUrn && (currentUrn == primaryUrn)) {
1241
            result = result || true;
1242
        }
1243
    });
1244
    return result;
1245
}
1246
var continuousScroll = function() {
1247
    var ajaxURL = jQuery("#next").attr("href");
1248
    jQuery.ajax({
1249
        url: ajaxURL,
1250
        success: function(html) {
1251
            if (html) {
1252
                jQuery(html).find("table tbody tr").each(function() {
1253
                    jQuery("#search-results tbody tr").last().parent().append(this);
1254
                });
1255
                if (jQuery(html).find("table tbody tr").length <= 0) {
1256
                    jQuery("#next").hide();
1257
                }
1258
            } else {
1259
                jQuery("#next").hide();
1260
            }
1261
        }
1262
    });
1263
    return false;
1264
}
1265
$(window).scroll(function() {
1266
    if ($(this).scrollTop() > 330) {
1267
        $(".tx-dpf-tab-container").addClass("sticky");
1268
    } else {
1269
        $(".tx-dpf-tab-container").removeClass("sticky");
1270
    }
1271
});
1272
1273
1274
var datepicker = function() {
1275
    var language = jQuery("div.tx-dpf[data-language]").first().attr("data-language");
1276
    if (!language) language = "en";
1277
    jQuery(".datetimepicker").datetimepicker({
1278
        icons: {
1279
            time: 'far fa-clock',
1280
            date: 'fas fa-calendar-alt',
1281
            up: 'fas fa-chevron-up',
1282
            down: 'fas fa-chevron-down',
1283
            previous: 'fas fa-chevron-left',
1284
            next: 'fas fa-chevron-right',
1285
            today: 'glyphicon glyphicon-screenshot',
1286
            clear: 'far fa-trash-alt',
1287
            close: 'fas fa-times'
1288
        },
1289
        useCurrent: false,
1290
        format: "DD.MM.YYYY",
1291
        locale: language,
1292
        keepInvalid: true,
1293
    }).on("keydown", function(e){
1294
        if (e.which == 13) {
1295
            $(".datetimepicker").closest("form").submit();
1296
        }
1297
    });
1298
}
1299
var isDate = function(value) {
1300
    if (value == "") return false;
1301
    var rxDatePattern = /^(\d{1,2})(\.)(\d{1,2})(\.)(\d{4})$/; //Declare Regex
1302
    var dtArray = value.match(rxDatePattern); // is format OK?
1303
    if (dtArray == null) return false;
0 ignored issues
show
Best Practice introduced by
Comparing dtArray to null using the == operator is not safe. Consider using === instead.
Loading history...
1304
    //Checks for mm/dd/yyyy format.
1305
    var dtMonth = dtArray[3];
1306
    var dtDay = dtArray[1];
1307
    var dtYear = dtArray[5];
1308
    if (dtMonth < 1 || dtMonth > 12) {
1309
        return false;
1310
    } else if (dtDay < 1 || dtDay > 31) {
1311
        return false;
1312
    } else if ((dtMonth == 4 || dtMonth == 6 || dtMonth == 9 || dtMonth == 11) && dtDay == 31) {
1313
        return false;
1314 View Code Duplication
    } else if (dtMonth == 2) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
1315
        var isleap = (dtYear % 4 == 0 && (dtYear % 100 != 0 || dtYear % 400 == 0));
0 ignored issues
show
Best Practice introduced by
Comparing dtYear % 4 to 0 using the == operator is not safe. Consider using === instead.
Loading history...
Best Practice introduced by
Comparing dtYear % 100 to 0 using the != operator is not safe. Consider using !== instead.
Loading history...
Best Practice introduced by
Comparing dtYear % 400 to 0 using the == operator is not safe. Consider using === instead.
Loading history...
1316
        if (dtDay > 29 || (dtDay == 29 && !isleap)) return false;
1317
    }
1318
    return true;
1319
}
1320
var documentListConfirmDialog = function(dialogId) {
1321
1322
    var title = '%s';
1323
1324
    jQuery(dialogId).modal({
1325
        show: false,
1326
        backdrop: 'static'
1327
    });
1328
    jQuery(dialogId).on("show.bs.modal", function(e) {
1329
        //jQuery(this).find(dialogId+"Document").attr("href", jQuery(e.relatedTarget).attr("href"));
1330
        jQuery(this).find(dialogId+"Document").attr("action", jQuery(e.relatedTarget).attr("href"));
1331
        var bodyText = jQuery(this).find(".modal-body p").html();
1332
        title = jQuery(e.relatedTarget).attr("data-documenttitle");
1333
        jQuery(this).find(".modal-body p").html(bodyText.replace("%s", title));
1334
        jQuery(e.relatedTarget).parent().parent().addClass("danger marked-for-removal");
1335
    });
1336
    jQuery(dialogId).on("hidden.bs.modal", function(e) {
0 ignored issues
show
Unused Code introduced by
The parameter e is not used and could be removed.

This check looks for parameters in functions that are not used in the function body and are not followed by other parameters which are used inside the function.

Loading history...
1337
        var bodyText = jQuery(this).find(".modal-body p").html();
1338
        jQuery(this).find(".modal-body p").html(bodyText.replace(title, "%s"));
1339
        jQuery(".marked-for-removal").removeClass("danger marked-for-removal");
1340
    });
1341
1342
    /*
1343
    //make reason mandatory
1344
    jQuery(dialogId+"Document").submit(function(e) {
1345
        var reason = jQuery(dialogId+"Document").find("textarea");
1346
        if (typeof reason !== 'undefined' && reason.length > 0) {
1347
            if (reason.val().trim().length == 0) {
1348
                reason.val("");
1349
                e.preventDefault();
1350
            }
1351
        }
1352
    });
1353
    */
1354
1355
    jQuery(dialogId+"ReasonSelect").on("change", function(e){
0 ignored issues
show
Unused Code introduced by
The parameter e is not used and could be removed.

This check looks for parameters in functions that are not used in the function body and are not followed by other parameters which are used inside the function.

Loading history...
1356
        jQuery(dialogId+"Reason").val(jQuery(this).val());
1357
    });
1358
1359
1360
1361
}
1362
1363
function addRemoveFileButton() {
1364
    $(".rem_file").unbind("click");
1365
    $(".rem_file").bind("click", function (evt) {
1366
        evt.preventDefault();
1367
        $(this).siblings(".input_file_upload").val("");
1368
    })
1369
}
1370
1371
1372
function autocompleteNothingFound(fieldId, groupIndex) {
1373
        var autocompleteInputField = $('.autocomplete[data-field="' + fieldId + '"][data-groupindex="' + groupIndex + '"]');
1374
1375
        if (autocompleteInputField.data("old_autocomplete_field_value")) {
1376
          autocompleteInputField.val(gndInputField.data("old_autocomplete_field_value"));
0 ignored issues
show
Bug introduced by
The variable gndInputField seems to be never declared. If this is a global, consider adding a /** global: gndInputField */ comment.

This checks looks for references to variables that have not been declared. This is most likey a typographical error or a variable has been renamed.

To learn more about declaring variables in Javascript, see the MDN.

Loading history...
1377
        } else {
1378
          autocompleteInputField.val();
1379
        }
1380
1381
        var autocompleteFieldId = autocompleteInputField.data("autocompletefield");
1382
        var linkedGroupIndex = autocompleteInputField.data("groupindex");
1383
        var autocompleteLinkedInputField = $('input[data-field="' + autocompleteFieldId + '"][data-groupindex="' + linkedGroupIndex + '"]');
1384
1385
        if (autocompleteLinkedInputField.data("old_autocomplete_field_id")) {
1386
          autocompleteLinkedInputField.val(autocompleteLinkedInputField.data("old_autocomplete_field_id"));
1387
        } else {
1388
          autocompleteLinkedInputField.val();
1389
        }
1390
1391
        /** global: form_error_msg_nothing_found */
1392
        jQuery('<div id="autocomplete-nothing-found" class="alert alert-warning" role="alert"><i class="fab fa-gripfire pull-right"></i>' + form_error_msg_nothing_found + '</div>').insertBefore(autocompleteInputField.closest(".form-container"));
0 ignored issues
show
Bug introduced by
The variable form_error_msg_nothing_found seems to be never declared. If this is a global, consider adding a /** global: form_error_msg_nothing_found */ comment.

This checks looks for references to variables that have not been declared. This is most likey a typographical error or a variable has been renamed.

To learn more about declaring variables in Javascript, see the MDN.

Loading history...
1393
1394
        autocompleteInputField.bind("keypress click", function () {
1395
            jQuery("#autocomplete-nothing-found").remove();
1396
        });
1397
1398
    autocompleteLinkedInputField.bind("keypress click", function () {
1399
        jQuery("#autocomplete-nothing-found").remove();
1400
    });
1401
1402
}
1403
1404
function setAutocomplete(fieldId, groupIndex) {
1405
    // autocomplete
1406
    var ajaxURL = $('.autocomplete[data-field="' + fieldId + '"][data-groupindex="' + groupIndex + '"]').attr("data-ajax");
1407
1408
    var autocompleteInputField = $('.autocomplete[data-field="' + fieldId + '"][data-groupindex="' + groupIndex + '"]');
1409
    var autocompleteFieldId = autocompleteInputField.data("autocompletefield");
1410
    var linkedGroupIndex = autocompleteInputField.data("groupindex");
1411
    var autocompleteLinkedInputField = $('input[data-field="' + autocompleteFieldId + '"][data-groupindex="' + linkedGroupIndex + '"]');
1412
1413
    autocompleteInputField.attr("data-old_autocomplete_field_value",autocompleteInputField.val());
1414
    autocompleteLinkedInputField.attr("data-old_autocomplete_field_id",autocompleteLinkedInputField.val());
1415
1416
    // Get the name of the parameter array (tx_dpf_...),
1417
    // the name depends on whether the call is from the frontend or the backend
1418
    var res = ajaxURL.match(/(tx_dpf\w+?)%/);
1419
    var paramName = "tx_dpf_kitodopublicationform[searchTerm]";
1420
    if (res && res[1]) {
1421
        paramName = res[1]+"[searchTerm]";
1422
    }
1423
1424
    $('.autocomplete[data-field="' + fieldId + '"][data-groupindex="' + groupIndex + '"]').autocomplete({
1425
        source: function (request, response) {
1426
1427
            $('input[data-field="' + autocompleteFieldId + '"][data-groupindex="' + linkedGroupIndex + '"]').val("");
1428
1429
            var requestData = {};
1430
            requestData[paramName] = request.term.replace(" ", "+");
1431
1432
         // console.log(ajaxURL);
1433
        //  console.log(params);
1434
1435
            $.ajax({
1436
                type: 'POST',
1437
                url: ajaxURL,
1438
                data: requestData,
1439
                dataType: 'json',
1440
                timeout: 10000,
1441
                success: function (data) {
1442
                   if (data) {
1443
                     response(data);
1444
                   } else {
1445
                      autocompleteNothingFound(fieldId, groupIndex);
1446
                      response([]);
1447
                   }
1448
                },
1449
                error: function (xhr, ajaxOptions, thrownError) {
1450
                  console.log(xhr.status);
0 ignored issues
show
Debugging Code introduced by
console.log looks like debug code. Are you sure you do not want to remove it?
Loading history...
1451
                  console.log(thrownError);
1452
                    autocompleteNothingFound(fieldId, groupIndex);
1453
                    response([]);
1454
                }
1455
            });
1456
        },
1457
        minLength: 3,
1458
        select: function (event, ui) {
1459
            autocompleteFieldId = jQuery(event.target).data("autocompletefield");
1460
            linkedGroupIndex = jQuery(event.target).data("groupindex");
1461
            $('input[data-field="' + autocompleteFieldId + '"][data-groupindex="' + linkedGroupIndex + '"]').val(ui.item.key);
1462
        },
1463
    }).autocomplete( "instance" )._renderItem = function( ul, item ) {
1464
        return $( "<li>" )
1465
            .append( "<div class='autocomplete'><span class='autocomplete-value' style='display:none;'>" + item.value + "</span>" +
1466
                "<span class='autocomplete-label'>" + item.label + "</span></div>"
1467
            )
1468
            .appendTo( ul );
1469
    };
1470
}
1471
1472
var previousNextFormPage = function() {
1473
1474
    $(".prev-next-buttons button").click(function (e) {
1475
        var activePage = $(".tx-dpf-tabs").find("li a.active").parent();
1476
        var newActivePage = activePage;
0 ignored issues
show
Unused Code introduced by
The assignment to variable newActivePage seems to be never used. Consider removing it.
Loading history...
1477
1478
        if ($(this).attr("id") == "next-form-page") {
1479
            newActivePage = activePage.next();
1480
        } else {
1481
            newActivePage = activePage.prev();
1482
        }
1483
1484
        if (newActivePage.length > 0) {
1485
            activePage.find("a").removeClass("active");
1486
            activePage.find("a").attr("aria-expanded", "false");
1487
            $(".tab-content").find("div.active").removeClass("active");
1488
1489
            newActivePage.find("a").addClass("active");
1490
            newActivePage.find("a").attr("aria-expanded", "true");
1491
            $(".tab-content").find(newActivePage.find("a").attr("href")).addClass("active");
1492
1493
            updatePrevNextButtons(newActivePage);
1494
1495
            $("html, body").animate({
1496
                scrollTop:$(".tx-dpf").offset().top
1497
            },"fast");
1498
        }
1499
1500
        e.preventDefault();
1501
1502
    });
1503
1504
    updatePrevNextButtons($(".tx-dpf-tabs a.active").parent());
1505
1506
    $(".tx-dpf-tabs a").click(function(){
1507
        updatePrevNextButtons($(this).parent());
1508
    });
1509
1510
}
1511
1512
var updatePrevNextButtons = function(activePage) {
1513
1514
    if (activePage !== undefined) {
1515
        if (activePage.prev().length < 1) {
1516
            $("#prev-form-page").addClass("disabled");
1517
        } else {
1518
            $("#prev-form-page").removeClass("disabled");
1519
        }
1520
        if (activePage.next().length < 1) {
1521
            $("#next-form-page").addClass("disabled");
1522
        } else {
1523
            $("#next-form-page").removeClass("disabled");
1524
        }
1525
    }
1526
}
1527
1528
var inputWithOptions = function() {
1529
1530
    $.widget( "custom.dropdownoptions", {
1531
        _create() {
1532
1533
            var availableTags = [];
1534
            var test = this.element
0 ignored issues
show
Unused Code introduced by
The variable test seems to be never used. Consider removing it.
Loading history...
1535
                .closest(".dropdown-options")
1536
                .find(".dropdown-options-values li")
1537
                .each(function(){
1538
                    if (jQuery(this).text().length > 0) {
1539
                        availableTags.push(jQuery(this).text());
1540
                    }
1541
                });
1542
1543
            this.element
1544
                .addClass( ".dropdown-options-input" )
1545
                .autocomplete({
1546
                    minLength: 0,
1547
                    source: availableTags
1548
                });
1549
1550
            this._createShowAllButton();
1551
        },
1552
        _createShowAllButton() {
1553
1554
            var input = this.element;
1555
1556
            wasOpen = false;
0 ignored issues
show
Bug introduced by
The variable wasOpen seems to be never declared. Assigning variables without defining them first makes them global. If this was intended, consider making it explicit like using window.wasOpen.
Loading history...
1557
1558
            input
1559
                .closest(".dropdown-options")
1560
                .find(".dropdown-options-toggle")
1561
                .on( "mousedown", function() {
1562
                    wasOpen = input.autocomplete( "widget" ).is( ":visible" );
0 ignored issues
show
Bug introduced by
The variable wasOpen seems to be never declared. Assigning variables without defining them first makes them global. If this was intended, consider making it explicit like using window.wasOpen.
Loading history...
1563
                })
1564
                .on( "click", function() {
1565
                    input.trigger( "focus" );
1566
                    if ( wasOpen ) {
1567
                        return;
1568
                    }
1569
                    input.autocomplete( "search", "" );
1570
1571
                });
1572
            input
1573
                .on( "click", function() {
1574
                    input.autocomplete( "search", "" );
1575
                });
1576
        }
1577
    });
1578
1579
    $( ".dropdown-options-input" ).dropdownoptions();
1580
}
1581
1582
var userSearch = function(group) {
1583
    if (group) {
1584
        $(group.find('.fis-user-search-input')).on('focus', delay(searchInputKeyupHandler, 500));
1585
        $(group.find('.fis-user-search-input')).on('keyup', delay(searchInputKeyupHandler, 500));
1586
        $(group.find('.fis-orga-search-input')).on('keyup', delay(searchInputKeyupHandler, 500));
1587
        $(group.find('.gnd-user-search-input')).on('keyup', delay(searchInputKeyupHandler, 500));
1588
        $(group.find('.ror-user-search-input')).on('keyup', delay(searchInputKeyupHandler, 500));
1589
        $(group.find('.zdb-user-search-input')).on('keyup', delay(searchInputKeyupHandler, 500));
1590
        $(group.find('.unpaywall-user-search-input')).on('keyup', delay(searchInputKeyupHandler, 500));
1591
        $(group.find('.orcid-user-search-input')).on('keyup', delay(searchInputKeyupHandler, 500));
1592
    } else {
1593
        $('.fis-user-search-input').on('focus', delay(searchInputKeyupHandler, 500));
1594
        $('.fis-user-search-input').on('keyup', delay(searchInputKeyupHandler, 500));
1595
        $('.fis-orga-search-input').on('keyup', delay(searchInputKeyupHandler, 500));
1596
        $('.gnd-user-search-input').on('keyup', delay(searchInputKeyupHandler, 500));
1597
        $('.ror-user-search-input').on('keyup', delay(searchInputKeyupHandler, 500));
1598
        $('.zdb-user-search-input').on('keyup', delay(searchInputKeyupHandler, 500));
1599
        $('.unpaywall-user-search-input').on('keyup', delay(searchInputKeyupHandler, 500));
1600
        $('.orcid-user-search-input').on('keyup', delay(searchInputKeyupHandler, 500));
1601
    }
1602
}
1603
1604
function delay(callback, ms) {
1605
    var timer = 0;
1606
    return function() {
1607
        var context = this, args = arguments;
1608
        clearTimeout(timer);
1609
        timer = setTimeout(function () {
1610
            callback.apply(context, args);
1611
        }, ms || 0);
1612
    };
1613
}
1614
1615
var searchInputKeyupHandler = function() {
1616
    var searchValue = $(this).val();
1617
    var groupIndex = $(this).data("groupindex");
0 ignored issues
show
Unused Code introduced by
The variable groupIndex seems to be never used. Consider removing it.
Loading history...
1618
    if (searchValue.length >= 3) {
1619
        let url = $(this).data("searchrequest");
1620
        let params = {};
1621
        params['tx_dpf_backoffice[searchTerm]'] = searchValue;
1622
        // type person or organisation
1623
        params['tx_dpf_backoffice[type]'] = $(this).closest('.modal').find("input[name^='searchTypeRadio']:checked").val();
1624
1625
        var radioType = $(this).closest('.modal').find("input[name^='searchTypeRadio']:checked").val();
1626
1627
        $.ajax({
1628
            type: "POST",
1629
            url: url,
1630
            data: params,
1631
            context: this,
1632
            success: function (data) {
1633
                var that = this;
1634
                var dataObject = JSON.parse(data);
1635
                var groupIndex = $(this).data("groupindex")
1636
                var hitListElement = $(this).parent().parent().find('.'+$(this).data("api").toLowerCase()+'-search-list-' + groupIndex + ' ul').html('');
1637
1638
                $.each(dataObject.entries, function (key, value) {
1639
                    var type = $(that).data("api").toLowerCase();
1640
                    var allData = value;
1641
1642
                    if ($(that).attr('class') === 'fis-user-search-input') {
1643
                        if (radioType == 'person') {
1644
                            if (value.organisationalUnits && value.organisationalUnits.length > 0) {
1645
                                var optionalText = value.organisationalUnits[0].titleDe;
1646
                                if (value.organisationalUnits[1]) {
1647
                                    optionalText = optionalText +', '+ value.organisationalUnits[1].titleDe
1648
                                }
1649
                            }
1650
                            hitListElement.append(listHtml(value.fullName, value.fisPersid, allData, optionalText));
0 ignored issues
show
Bug introduced by
The variable optionalText does not seem to be initialized in case value.organisationalUnit...ationalUnits.length > 0 on line 1644 is false. Are you sure the function listHtml handles undefined variables?
Loading history...
1651
                        } else if (radioType == 'organisation'){
1652
                            hitListElement.append(listHtml(value.titleDe + ' (' + value.parentOrgaName + ')', value.id, allData));
1653
                        }
1654
                    } else if ($(that).attr('class') === 'fis-orga-search-input') {
1655
                        hitListElement.append(listHtml(value.titleDe, value.id, allData));
1656
                    } else if ($(that).attr('class') === 'gnd-user-search-input') {
1657
                        if (radioType == 'person') {
1658
                            var professions = '';
1659
                            var date = '';
1660
1661
                            if (value.professionOrOccupation !== undefined) {
1662
                                $.each(value.professionOrOccupation, function (key, value) {
1663
                                    professions += value.label + ', ';
1664
                                });
1665
                                professions = professions.slice(0, -2);
1666
                            }
1667
                            if (value.dateOfBirth) {
1668
                                date = value.dateOfBirth;
1669
                            }
1670
                            if (value.dateOfDeath) {
1671
                                date += ' - ' + value.dateOfDeath;
1672
                            }
1673
                            var optionalText = '';
0 ignored issues
show
Comprehensibility Naming Best Practice introduced by
The variable optionalText already seems to be declared on line 1645. Consider using another variable name or omitting the var keyword.

This check looks for variables that are declared in multiple lines. There may be several reasons for this.

In the simplest case the variable name was reused by mistake. This may lead to very hard to locate bugs.

If you want to reuse a variable for another purpose, consider declaring it at or near the top of your function and just assigning to it subsequently so it is always declared.

Loading history...
1674
                            if (date) {
1675
                                optionalText = date;
1676
                            }
1677
                            if (professions) {
1678
                                if (date) {
1679
                                    optionalText += ', ';
1680
                                }
1681
                                optionalText += professions.trim();
1682
                            }
1683
                        }
1684
1685
                        hitListElement.append(listHtml(value.preferredName, value.gndIdentifier, allData, optionalText));
1686
                    } else if ($(that).attr('class') === 'ror-user-search-input') {
1687
                        var optionalText = '';
0 ignored issues
show
Comprehensibility Naming Best Practice introduced by
The variable optionalText already seems to be declared on line 1645. Consider using another variable name or omitting the var keyword.

This check looks for variables that are declared in multiple lines. There may be several reasons for this.

In the simplest case the variable name was reused by mistake. This may lead to very hard to locate bugs.

If you want to reuse a variable for another purpose, consider declaring it at or near the top of your function and just assigning to it subsequently so it is always declared.

Loading history...
1688
1689
                        if (allData.type) {
1690
                            optionalText += allData.type;
1691
                        }
1692
                        if (allData.aliases) {
1693
                            optionalText += allData.aliases;
1694
                        }
1695
1696
                        hitListElement.append(listHtml(value.name, value.id, allData, optionalText));
1697
                    } else if ($(that).attr('class') === 'zdb-user-search-input') {
1698
                        hitListElement.append(listHtml(value.title, value.identifier, allData, value.publisher));
1699
                    } else if ($(that).attr('class') === 'unpaywall-user-search-input') {
1700
                        hitListElement.append(listHtml(value.title, value.doi, allData, value.best_oa_location.url_for_landing_page, value.oa_status));
1701
                    } else if ($(that).attr('class') === 'orcid-user-search-input') {
1702
                        hitListElement.append(listHtml(value["given-names"] + ' ' + value["family-names"], value["orcid-id"], allData, value["orcid-id"]));
1703
                    }
1704
1705
                });
1706
                addFoundUserData();
1707
            }
1708
        });
1709
    }
1710
}
1711
1712
var listHtml = function (name, id, all = '', optionalText = '', color = '') {
1713
    JSON.stringify(all).replace(/"/g, '');
1714
1715
    if (color) {
1716
        colorHtml = '('+color+')';
0 ignored issues
show
Bug introduced by
The variable colorHtml seems to be never declared. Assigning variables without defining them first makes them global. If this was intended, consider making it explicit like using window.colorHtml.
Loading history...
1717
    } else {
1718
        colorHtml = '';
1719
    }
1720
1721
    var text = '';
1722
    if (optionalText) {
1723
        var text = ' (' + optionalText + ') ';
0 ignored issues
show
Comprehensibility Naming Best Practice introduced by
The variable text already seems to be declared on line 1721. Consider using another variable name or omitting the var keyword.

This check looks for variables that are declared in multiple lines. There may be several reasons for this.

In the simplest case the variable name was reused by mistake. This may lead to very hard to locate bugs.

If you want to reuse a variable for another purpose, consider declaring it at or near the top of your function and just assigning to it subsequently so it is always declared.

Loading history...
1724
    }
1725
    var orgaName = '';
1726
    if (all.organisationalUnits !== undefined) {
1727
        $.each(all.organisationalUnits, function(key, value) {
1728
            orgaName += value.titleDe + ', ';
1729
        });
1730
        orgaName = orgaName.slice(0, -2);
1731
    }
1732
1733
    return '<li style="margin-bottom:1rem;" class="container">' +
1734
        '<div class="row">' +
1735
        '<div class="col"><button style="margin-right:1rem;" class="btn btn-s btn-info found-user-add" type="button" data-id="' + id + '" data-surname="'+all.surname+'" data-givenname="'+all.givenName+'" data-organame="'+orgaName+'">' +
1736
        'Übernehmen' +
1737
        '</button></div>' +
1738
        '<div class="col-6">' +
1739
        name + text + colorHtml +
1740
        '</div>' +
1741
        '</div>' +
1742
        '</li>';
1743
}
1744
1745
var addFoundUserData = function () {
1746
    $('.found-user-add').on('click', function () {
1747
        var input = $(this).closest('.modal-body').find('input');
1748
1749
        // user setting modal
1750
        if (input.data('usersettings') == '1') {
1751
            $('#fisPersId').val($(this).data('id'));
1752
            $('#firstName').val($(this).data('givenname'));
1753
            $('#lastName').val($(this).data('surname'));
1754
            $('#orgaName').val($(this).data('organame'));
1755
            $(this).closest('.modal').modal('hide');
1756
        } else if (input.data('usersettings') == 'extSearch') {
1757
            $('#search-field-default-value').val($(this).data('id'));
1758
            $(this).closest('.modal').modal('hide');
1759
        } else {
1760
            setDataRequest(input.data('datarequest'), $(this).data('id'), input);
1761
        }
1762
1763
    });
1764
}
1765
1766
var setDataRequest = function(url, dataId, context) {
1767
1768
    let params = {};
1769
    params['tx_dpf_backoffice[dataId]'] = dataId;
1770
    params['tx_dpf_backoffice[groupId]'] = context.data('group');
1771
    params['tx_dpf_backoffice[groupIndex]'] = context.data('groupindex');
1772
    params['tx_dpf_backoffice[fieldIndex]'] = 0;
1773
    params['tx_dpf_backoffice[pageId]'] = context.data('page');
1774
    params['tx_dpf_backoffice[type]'] = context.closest('.modal').find("input[name^='searchTypeRadio']:checked").val();
1775
1776
    $.ajax({
1777
        type: "POST",
1778
        url: url,
1779
        data: params,
1780
        dataType: 'json',
1781
        success: function (data) {
1782
            var newKeyMapping = new Map();
1783
            // fill out data for each key
1784
            for (var key in data) {
0 ignored issues
show
Complexity introduced by
A for in loop automatically includes the property of any prototype object, consider checking the key using hasOwnProperty.

When iterating over the keys of an object, this includes not only the keys of the object, but also keys contained in the prototype of that object. It is generally a best practice to check for these keys specifically:

var someObject;
for (var key in someObject) {
    if ( ! someObject.hasOwnProperty(key)) {
        continue; // Skip keys from the prototype.
    }

    doSomethingWith(key);
}
Loading history...
1785
                var splitId = key.split("-");
1786
                // key without the last index (field index)
1787
                var keyWithoutFieldIndex = splitId[0] + '-' + splitId[1] + '-' + splitId[2] + '-' + splitId[3];
1788
                var isFieldRepeatable = $('.' + keyWithoutFieldIndex + '-' + '0').parent().parent().find('.add_field').length;
1789
1790
                if($('.' + key).length != 0 && $('.' + key).val() == '' || $('.' + key).length != 0 && $('.' + key).val() != '' && !isFieldRepeatable) {
0 ignored issues
show
Best Practice introduced by
Comparing $("." + key).length to 0 using the != operator is not safe. Consider using !== instead.
Loading history...
1791
                    // form field is empty and exists or form field is not empty and not repeatable, overwrite!
1792
                    $('.' + key).val(data[key]).change();
1793
                } else if ($('.' + key).length != 0 && $('.' + key).val() != '' && isFieldRepeatable) {
1794
                    // form field exists and is not empty
1795
                    // add new form input
1796
                    $('.' + keyWithoutFieldIndex + '-' + '0').parent().parent().find('.add_field').click();
1797
1798
                    // count repeated fields if not counted already
1799
                    var k = newKeyMapping.get(keyWithoutFieldIndex);
1800
                    if (typeof k == 'undefined') {
1801
                        var i = 0;
1802
                        while ($('.' + keyWithoutFieldIndex + '-' + i).length) {
1803
                            i++;
1804
                        }
1805
                    } else {
1806
                        i = k + 1;
1807
                    }
1808
1809
                    var newKey = keyWithoutFieldIndex + '-' + i;
1810
                    newKeyMapping.set(keyWithoutFieldIndex, i);
1811
1812
                    isElementLoaded('.' + newKey, key, function (element, fieldKey) {
1813
                        $(element).val(data[fieldKey]).change();
1814
                    });
1815
1816
                } else {
1817
                    // if key does not exist check if field is repeatable
1818
                    splitId = key.split("-");
1819
                    var datakey = key;
1820
                    if (splitId[4] > 0) {
1821
                        var k = newKeyMapping.get(keyWithoutFieldIndex);
0 ignored issues
show
Comprehensibility Naming Best Practice introduced by
The variable k already seems to be declared on line 1799. Consider using another variable name or omitting the var keyword.

This check looks for variables that are declared in multiple lines. There may be several reasons for this.

In the simplest case the variable name was reused by mistake. This may lead to very hard to locate bugs.

If you want to reuse a variable for another purpose, consider declaring it at or near the top of your function and just assigning to it subsequently so it is always declared.

Loading history...
1822
                        if (typeof k != 'undefined') {
1823
                            datakey = key;
1824
                            key = keyWithoutFieldIndex + '-' + (k + 1);
1825
                            newKeyMapping.set(keyWithoutFieldIndex, (k + 1));
1826
                        }
1827
                        // add new form input
1828
                        $('.' + keyWithoutFieldIndex + '-' + '0').parent().parent().find('.add_field').click();
1829
                        isElementLoaded('.' + key, datakey, function (element, fieldKey) {
1830
                            $(element).val(data[fieldKey]).change();
1831
                        });
1832
                    }
1833
                }
1834
            }
1835
        }
1836
    });
1837
    context.closest('.modal').modal('hide');
1838
}
1839
1840
var isElementLoaded = function (element, fieldKey, callback, counter = 0) {
1841
    if ($(element).length) {
1842
        callback($(element), fieldKey);
1843
    } else {
1844
        if (counter < 5) {
1845
            setTimeout(function () {
1846
                isElementLoaded(element, fieldKey, callback, counter++)
1847
            }, 500);
1848
        } else {
1849
            console.error("Field not repeatable or doesnt exist");
1850
        }
1851
    }
1852
}
1853
1854
var addMyUserData = function() {
1855
    $('.addMyData').on('click', function () {
1856
        setDataRequest($(this).data('ajax'), $(this).data('personid'), $(this));
1857
    });
1858
1859
    jQuery("[data-objecttype='fispersonid']").on('change', function() {
1860
        var fisPersonIdentifiers = getFisPersonIdentifiers();
1861
        toggleAddMyUserDataButton(fisPersonIdentifiers);
1862
    });
1863
1864
    var fisPersonIdentifiers = getFisPersonIdentifiers();
1865
    toggleAddMyUserDataButton(fisPersonIdentifiers);
1866
1867
    jQuery("[data-objecttype='fispersonid']").on('keyup', function() {
1868
        var fisPersonIdentifiers = getFisPersonIdentifiers();
1869
        toggleAddMyUserDataButton(fisPersonIdentifiers);
1870
    });
1871
}
1872
1873
var getFisPersonIdentifiers = function() {
1874
    fisPersonIdentifiers = [];
0 ignored issues
show
Bug introduced by
The variable fisPersonIdentifiers seems to be never declared. Assigning variables without defining them first makes them global. If this was intended, consider making it explicit like using window.fisPersonIdentifiers.
Loading history...
1875
    jQuery("[data-objecttype='fispersonid']").each(function() {
1876
        fisPersonIdentifiers.push(jQuery(this).val());
1877
    });
1878
1879
    return fisPersonIdentifiers;
1880
}
1881
1882
var toggleAddMyUserDataButton = function(fisPersonIdentifiers) {
1883
    var fisPersonId = jQuery('.addMyData').data('personid');
1884
    if (fisPersonIdentifiers.includes(fisPersonId)) {
1885
        jQuery('button.addMyData').hide();
1886
    } else {
1887
        jQuery('button.addMyData').show();
1888
    }
1889
}
1890
1891
var searchAgain = function (context) {
1892
    searchInputKeyupHandler.call(context);
1893
}
1894
1895
var userSearchModalFillout = function() {
1896
1897
    $('.FisSearchModal').on('hidden.bs.modal', function() {
1898
            jQuery(this).find('.fis-user-search-input').val('');
1899
            jQuery(this).find('.fis-search-results').html('');
1900
    });
1901
1902
    $('.FisSearchModal').on('shown.bs.modal', function () {
1903
        //jQuery(this).find("#orgaRadio").prop('checked', false);
1904
        //jQuery(this).find("#personRadio").prop('checked', true);
1905
        var surname = jQuery(this).closest('fieldset').find('[data-objecttype=surname]').val();
1906
        if (typeof surname !== 'undefined') {
1907
            if (surname.length > 0) {
1908
                jQuery(this).find('.fis-user-search-input').val(surname);
1909
            }
1910
        }
1911
    });
1912
1913
    $('.UnpaywallSearchModal').on('shown.bs.modal', function () {
1914
        var doiValue = $(this).closest('fieldset').find('*[data-objecttype="unpaywallDoi"]').val();
1915
        $(this).find('.unpaywall-user-search-input').val(doiValue);
1916
        searchAgain($(this).closest('.modal').find("input[type=text]")[0]);
1917
    });
1918
}
1919
1920
// Call methods for API Token generation
1921
var apiTokenEvents = function() {
1922
    $('#apiTokenGenerate').on('click', function () {
1923
        var url = $(this).data('generatetoken');
1924
        $.ajax({
1925
            type: "GET",
1926
            url: url,
1927
            dataType: 'json',
1928
            success: function (data) {
1929
                $('#showApiToken').text(data.apiToken);
1930
            }
1931
        });
1932
    });
1933
1934
    $('#apiTokenRemove').on('click', function () {
1935
        var url = $(this).data('removetoken');
1936
        $.ajax({
1937
            type: "GET",
1938
            url: url,
1939
            dataType: 'json',
1940
            success: function (data) {
1941
                if (data.success) {
1942
                    $('#apiTokenRemove').hide();
1943
                }
1944
            }
1945
        });
1946
    });
1947
}
1948
1949
// -------------------------------------------------------
1950
// Document ready
1951
// -------------------------------------------------------
1952
$(document).ready(function() {
1953
1954
    bsCustomFileInput.init();
0 ignored issues
show
Bug introduced by
The variable bsCustomFileInput seems to be never declared. If this is a global, consider adding a /** global: bsCustomFileInput */ comment.

This checks looks for references to variables that have not been declared. This is most likey a typographical error or a variable has been renamed.

To learn more about declaring variables in Javascript, see the MDN.

Loading history...
1955
1956
    jQuery("#new-document-form").trigger("reset");
1957
    documentListConfirmDialog("#confirmDiscard");
1958
    documentListConfirmDialog("#confirmReleasePublish");
1959
    documentListConfirmDialog("#confirmReleaseActivate");
1960
    documentListConfirmDialog("#confirmActivate");
1961
    documentListConfirmDialog("#confirmInactivate");
1962
    documentListConfirmDialog("#confirmRestore");
1963
    documentListConfirmDialog("#confirmDelete");
1964
    documentListConfirmDialog("#confirmDeleteLocally");
1965
    documentListConfirmDialog("#confirmDeleteLocallySuggestion");
1966
    documentListConfirmDialog("#confirmDeleteWorkingCopy");
1967
    documentListConfirmDialog("#confirmRegister");
1968
    documentListConfirmDialog("#confirmPostpone");
1969
1970
    batchConfirmDialog("BatchSetInProgress");
1971
    batchConfirmDialog("BatchRegister");
1972
    batchConfirmDialog("BatchRemove");
1973
    batchConfirmDialog("BatchReleaseValidated");
1974
    batchConfirmDialog("BatchReleaseUnvalidated");
1975
    batchConfirmDialog("BatchBookmark");
1976
1977
    removeBookmarkHandler.init();
1978
    addBookmarkHandler.init();
1979
    batchSelectHandler.init();
1980
1981
    itemsPerPageHandler.init();
1982
1983
    extendedSearch.init();
1984
    saveExtendedSearch.init();
1985
    openExtendedSearch.init();
1986
1987
    userNotifcationSettings.init();
1988
1989
    documentFormGroupSelector.init();
1990
1991
    doctypeChange.init();
1992
1993
    datepicker();
1994
    jQuery('[data-toggle="tooltip"]').tooltip();
1995
    var $disableForm = jQuery("form[data-disabled]").attr("data-disabled");
1996
    if ($disableForm) {
1997
        jQuery(".input-field").each(function() {
1998
            jQuery(this).attr("disabled", "disabled");
1999
        });
2000
        jQuery(".rem_file_group").each(function() {
2001
            jQuery(this).attr("disabled", "disabled");
2002
        });
2003
        jQuery(".add_file_group").each(function() {
2004
            jQuery(this).attr("disabled", "disabled");
2005
        });
2006
        jQuery(".input_file_upload").each(function() {
2007
            jQuery(this).attr("disabled", "disabled");
2008
        });
2009
        jQuery(".add_field").each(function() {
2010
            jQuery(this).attr("disabled", "disabled");
2011
        });
2012
        jQuery(".add_group").each(function() {
2013
            jQuery(this).attr("disabled", "disabled");
2014
        });
2015
        jQuery(".rem_field").each(function() {
2016
            jQuery(this).attr("disabled", "disabled");
2017
        });
2018
        jQuery(".rem_group").each(function() {
2019
            jQuery(this).attr("disabled", "disabled");
2020
        });
2021
        jQuery(".fill_out_service_urn").each(function() {
2022
            jQuery(this).attr("disabled", "disabled");
2023
        });
2024
    }
2025
    buttonFillOutServiceUrn();
2026
    jQuery(".tx-dpf").on("click", ".rem_group", function() {
2027
        jQuery(this).parents("fieldset").fadeOut(300, function() {
2028
            jQuery(this).remove();
2029
            var fisPersonIdentifiers = getFisPersonIdentifiers();
2030
            toggleAddMyUserDataButton(fisPersonIdentifiers);
2031
        });
2032
        return false;
2033
    });
2034
    jQuery(".tx-dpf").on("click", ".rem_file_group", deleteFile);
2035
    jQuery(".tx-dpf").on("click", ".rem_field", function() {
2036
        var dataIndex = jQuery(this).data("index");
0 ignored issues
show
Unused Code introduced by
The variable dataIndex seems to be never used. Consider removing it.
Loading history...
2037
        var dataField = jQuery(this).data("field");
0 ignored issues
show
Unused Code introduced by
The variable dataField seems to be never used. Consider removing it.
Loading history...
2038
        jQuery(this).parents(".form-group").fadeOut(300, function() {
2039
            jQuery(this).remove();
2040
        });
2041
        return false;
2042
    });
2043
    // Add metadata group
2044
    jQuery(".tx-dpf").on("click", ".add_group", function(e) {
2045
        addGroup(e.target);
2046
        return false;
2047
    });
2048
    jQuery(".tx-dpf").on("click", ".add_file_group", function(e) {
2049
        addGroup(e.target);
2050
        return false;
2051
    });
2052
2053
    jQuery(".tx-dpf").on("click", ".add_field", addField);
2054
    jQuery(".tx-dpf").on("click", ".fill_out_service_urn", fillOutServiceUrn);
2055
    jQuery(".tx-dpf").on("keyup", "input.urn", buttonFillOutServiceUrn);
2056
    jQuery(".tx-dpf").on("click", "#next", continuousScroll);
2057
    jQuery(".form-submit").on("click", "#save", validateFormAndSave);
2058
2059
    if (
2060
        typeof(deactivate_mandatory_check_on_save_locally) == "undefined"
0 ignored issues
show
Bug introduced by
The variable deactivate_mandatory_check_on_save_locally seems to be never declared. If this is a global, consider adding a /** global: deactivate_m...heck_on_save_locally */ comment.

This checks looks for references to variables that have not been declared. This is most likey a typographical error or a variable has been renamed.

To learn more about declaring variables in Javascript, see the MDN.

Loading history...
2061
        || deactivate_mandatory_check_on_save_locally.length == 0
0 ignored issues
show
Best Practice introduced by
Comparing deactivate_mandatory_check_on_save_locally.length to 0 using the == operator is not safe. Consider using === instead.
Loading history...
2062
    ) {
2063
        jQuery(".form-submit").on("click", "#saveLocalDocument", validateFormAndSave);
2064
        jQuery(".form-submit").on("click", "#saveCreate", validateFormAndSave);
2065
    }
2066
2067
    jQuery(".form-submit").on("click", "#validate", validateFormOnly);
2068
2069
    // hide 'more results' link
2070
    var countResults = $("#search-results :not(thead) tr").length;
2071
    var resultCount = $("#next").data("resultCount");
2072
2073
    if (countResults < resultCount) {
2074
        jQuery("#next").hide();
2075
    }
2076
2077
    addRemoveFileButton();
2078
2079
    previousNextFormPage();
2080
2081
    var autocomplete = jQuery(".autocomplete");
2082
    if(autocomplete.length > 0) {
2083
        autocomplete.each(function() {
2084
            setAutocomplete(jQuery(this).data("field"),  jQuery(this).data("groupindex"));
2085
        });
2086
    }
2087
2088
    selectFilter('doctype-filter');
2089
    selectFilter('persons-filter', true);
2090
    selectFilter('aliasState-filter');
2091
    selectFilter('year-filter', true);
2092
    selectFilter('hasFiles-filter');
2093
    selectFilter('universityCollection-filter');
2094
    selectFilter('creatorRole-filter');
2095
2096
    // Remove the title hover for the filter elements.
2097
    jQuery(".select2-selection__rendered").each(function(){
2098
        jQuery(this).removeAttr("title");
2099
    });
2100
2101
    selectSort();
2102
2103
    toggleBulkImportRecord();
2104
    toggleBulkImportAuthorSearch();
2105
    toggleDiscardedFilter();
2106
    toggleBookmarksOnly();
2107
    inputWithOptions();
2108
2109
    apiTokenEvents();
2110
2111
    userSearch();
2112
    addMyUserData();
2113
    userSearchModalFillout();
2114
    $('.modal').on('shown.bs.modal', function() {
2115
        $(this).find('[autofocus]').focus();
2116
        // new search if checkbox has changed
2117
        $(this).find("#orgaRadio").on('change', function () {
2118
            searchAgain($(this).closest('.modal').find("input[type=text]")[0]);
2119
        });
2120
        $(this).find("#personRadio").on('change', function () {
2121
            searchAgain($(this).closest('.modal').find("input[type=text]")[0]);
2122
        });
2123
    });
2124
2125
    $('.double-scroll').doubleScroll();
2126
});
2127